Laravel validation not exists in table
Asked Answered
A

1

7

I have two tables, first one is students and second one is lesson_student table. They have m2m relationship between students and lessons tables. I want to check, if student_id exists in students table and not exists in lesson_student table, insert it. I use exists to check in students table but i have no idea how to check it is not exists in lesson_student table.

public function store(Request $request, Lesson $lesson) {
    $rules = [
        'student_id'    => 'required|exists:students,id'
    ];

    $this->validate($request, $rules);

    $lesson->students()->attach($request->student_id);
    return $this->showAll($lesson->students);
}

btw i am using laravel 5.6

Adjacent answered 18/6, 2018 at 17:28 Comment(2)
Share your DB structure and check only in one table lesson_studentEsquiline
lesson_student table has lesson_id and student_id only, it is pivot table. @C2486Adjacent
F
14

Probably you want to use unique rule like this:

$rules = [
   'student_id' => 'required|exists:students,id|unique:lesson_student:student_id'
]

EDIT

As you updated and explained in comment you want to have unique student_id and lesson_id in lesson_student table. Then you can use:

$rules = [
    'student_id' => [
       'required',
       'exists:students,id',
        \Illuminate\Validation\Rule::unique('lesson_student', 'student_id')
             ->where('lesson_id', $lesson->id),
     ]
];
Followup answered 18/6, 2018 at 17:45 Comment(3)
student_id is not unique in lesson_student table. lesson_student table has lesson_id and student_id. It is a pivot table. lesson_id and student_id both of them are unique.Adjacent
@Adjacent I thought so, but you haven't mentioned this in your question. So where do you have your lesson id when running this request ?Latrena
Nabialek my bad, you are right. I missed it. I updated question with full code. Sorry.Adjacent

© 2022 - 2024 — McMap. All rights reserved.