php - Laravel 验证表中不存在

标签 php laravel laravel-5 laravel-5.6 laravel-validation

我有两个表,第一个是学生表,第二个是lesson_student表。学生和类(class)表之间存在 m2m 关系。我想检查,如果student_id存在于students表中但不存在于lesses_student表中,则将其插入。我使用 exists 来检查学生表,但我不知道如何检查它在 Lesson_student 表中是否不存在。

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);
}

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

最佳答案

您可能想使用unique规则如下:

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

编辑

正如您在评论中更新和解释的那样,您希望在 lesson_student 表中拥有唯一的 Student_id 和 Lesson_id。然后你可以使用:

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

关于php - Laravel 验证表中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50914670/

相关文章:

php - 在 php 脚本中使用 curl

PHP 7.4 修剪字符串变量之间的空格

php - Laravel/PHP MySQL使用Json一对多关系

php - 找不到 Laravel 5.1 嵌套 Controller 类

php - Codeigniter 中的冲突 mysql 查询

php - 解码奇怪且可能是恶意的 PHP 代码

php - 兼容性 AES-256-CBC Node/Laravel

Laravel Jetstream 与 Intertia 不返回用户

laravel - View 中 undefined variable

laravel - 方法 Illuminate\View\View::response 不存在