How to validate foreign keys (as UUID) in attached elements like below:
$user->languages()->attach([
'9a347a21-b6db-42ae-85a5-24a270946eec' => [ // UUID of language
'additional_field' => 2,
'additional_field2' => '',
],
'9a347a21-e0b8-4475-a262-e63042d1a6f6' => [ // UUID of language
'additional_field' => 321,
'additional_field2' => 'aaa bb c',
],
]);
My relation in User looks like:
public function languages(): BelongsToMany
{
return $this->belongsToMany(Language::class)
->using(UserLanguage::class)
->withPivot(['additional_field', 'additional_field2']);
}
I can validate by
languageslanguages.*.additional_fieldlanguages.*.additional_field2
But how to validate UUID in above example is exists in Language model?
The
existsvalidation should work the same way as it does with regular numeric ids. However, it gets tricky to validate if you pass the ids as array keys.One way I'd do it is like this
The data sent would look like
And the way you could easily insert stuff in the endpoint with the validated request would be
Assuming you send the data like this:
The only way I can think of that would validate the keys without making a new Rule would be to use a Callback, like the
validatoror theFormRequest'safter()method.Laravel 10.x - Validation - Performing Additional Validation on Form Requests