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