Search code examples
laravellaravel-validation

How to use Rule:unique with array of values compared to another column in laravel?


i have a request for array of values and i validate it with the following code

$request->validate([
  'doctor_id.*'     => ['required'],
  'doctor_id'     => [Rule::unique('project_orders')->where(function ($query) use ($student) {
    $query->where('student_id', $student->id);
  })],
]);

but the unique validation doesn't work and the data was inserted to the table with duplication

i want the doctor_id field to be unique with the student_id column, what should be the correct rule?

any help please ?


Solution

  • First you need to do validation on database level, so you will add in your migration

    $table->unique(['doctor_id', 'student_id']);
    

    This will make sure that there will be no duplication for same doctor_id and student_id values

    Then in your validation layer you will add

    $request->validate([
      'doctor_id.*' => 'unique:project_orders,doctor_id,NULL,id,student_id,'.$student->id,
    ]);