表中不存在 Laravel 验证

Nev*_*ore 4 php laravel laravel-5 laravel-validation laravel-5.6

我有两个表,第一个是学生,第二个是课程_学生表。他们在学生和课程表之间有 m2m 关系。我想检查一下,如果 student_id 存在于 student 表中并且不存在于 course_student 表中,请将其插入。我exists过去常常检查学生表,但我不知道如何检查它在课程表中不存在。

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);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我正在使用 Laravel 5.6

Mar*_*łek 9

可能你想使用这样的独特规则:

$rules = [
   'student_id' => 'required|exists:students,id|unique:lesson_student:student_id'
]
Run Code Online (Sandbox Code Playgroud)

编辑

当您在评论中更新和解释时,您希望在lesson_student表中拥有唯一的 student_id 和 course_id 。然后你可以使用:

$rules = [
    'student_id' => [
       'required',
       'exists:students,id',
        \Illuminate\Validation\Rule::unique('lesson_student', 'student_id')
             ->where('lesson_id', $lesson->id),
     ]
];
Run Code Online (Sandbox Code Playgroud)