Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AndrykVP's avatar

Validating uniqueness of JSON column with Form Validation

Hello everyone, I'm relatively new to Laravel and PHP in general, and right now I need some help with validation. I hope someone can help me.

My project uses a coordinates column that is a json type. For clarification, it doesn't use real world coordinates, but rather an array like this:

{
   "atmosphere": {
      "x": 0,
      "y": 0
   },
   "ground": {
      "x": 0,
      "y": 0
   }
}

These should be unique coordinates so I would like to know if and how it's possible to validate this using Laravel's Form Validation.

I have this form request:

public function rules()
    {
        $id = $this->segment(3);

        return [
            'id' => ['required','integer',Rule::unique('locations')->ignore($id)],
            'market_id' => 'required|integer',
            'coordinates' => ['required','array',Rule::unique('locations')->ignore($id)],
            'name' => 'nullable|string',
            'owner' => 'nullable|string',
        ];
    }

The rest of the validation works fine, except for the coordinates field, since I can continue creating models with the same coordinates over and over.

I tried using the rule json instead of array, and casting it with this function:

protected function prepareForValidation()
{
    $this->merge([
        'coordinates' => json_encode($this->coordinates),
    ]);
}

But it still doesn't do the validation, and instead saves the entry with backslashes, rather than a clean array. My guess is that I need a custom Rule but I'm not exactly sure how to do it.

I'll appreciate any insight you guys can give me. Thanks in advance

0 likes
3 replies
aboozar_k's avatar

hi my database have a "optios" table and I will be to validation a one property in the json field that name is "details". for this work I write this line in rules function in FormRequest:

'slug' => ['unique:options,details->slug']

"slug" is input of my form "unique" is key word of laravel for not repeated "options" is my table "details->slug" is property "slug" in details column

and when duplicate slug insert input => laravel say me : "The slug has already been taken."

4 likes
AndrykVP's avatar

@aboozar_k That sounds exactly like what I want. I will give it a try! Thanks!

Just for the record, what version of Laravel are you using?

GGoodall's avatar

@aboozar_k Works like a charm thanks! This is the array rules that I used:

$locale = Tag::getLocale();

return [
  'name' => ['required', 'string', 'max:255', Rule::unique('tags', "name->$locale")],
];

It makes sure that the tag name is unique per locale in the JSON column. In my case trying to re-add "consequatur quas earum illo quaerat" with the JSON looking like: { "en": "consequatur quas earum illo quaerat" } made the validation fail.

Edit: Tested on Laravel 11.x

Please or to participate in this conversation.