Home > Blockchain >  Validation in Laravel on relationship
Validation in Laravel on relationship

Time:07-07

In Laravel, I have a persons model that has a many-to-many relationship with its group. The person's name needs to be unique in its group but not on the persons table. How would ensure that?

My validation is done in the controller store method using $request->validate(['name => ...

I currently save the new person in a controller using simply - Person::create([...

CodePudding user response:

My simple approach is using a composite primary keys on pivot table and use basic exception handling like try catch stuff whenever inserting data is fail due to migration

$table->foreignId('group_id') // Add any modifier to this column
$table->foreignId('person_id')  // Add any modifier to this column
$table->primary(['group_id', 'person_id']);

If you want to do it on controller, make sure to setup relationship. Then just use Rule::notIn() Validation

'name' => [
   'required',
   Rule::notIn(/* put your logic here */),
],

CodePudding user response:

You can use 'exist' rule in Laravel Validation like that: 'name' => 'exists:group,name,person_id,'.$id For more info you can check here: https://laravel.com/docs/5.1/validation#rule-exists

  • Related