Laravel验证在表中不存在 - php

我有两个表,第一个是学生,第二个是lesson_student表。他们在学生和课程表之间具有m2m关系。我想检查一下,是否student_id存在于students表中,而不存在于lesson_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),
     ]
];

检查对象是否已在集合中-Laravel - php

当我循环一系列不同的结果时,我希望将对象添加到新集合中。查询:$osRed = Item::where('category', 'Hardware') ->where(function ($query) { $query->where('operating_system', '…

PHP Laravel从另一个驱动器读取文件 - php

我目前正在学习Laravel。我想知道是否有一种方法可以在Laravel中使用Storage::从另一个硬盘访问文件(使用Windows)。例如,我在驱动器C:上安装了带有Laravel的Xampp,但是我想访问网站目录之外的E:上的文件。我试过使用Storage::files('E:')和File::files('E:…

Laravel 5排序具有关系的雄辩模型 - php

我有一个要基于关系属性进行排序的模型。主模型Resultado具有类型respondente的关系belongsTo,而respondente具有关系usuario。我想获取具有这些关系的Resultado并按usuario name属性(列)对结果进行排序。我试过了$resultados = Diagnostico\Resultado::with(…

Laravel Blade模板尝试获取非对象的属性时如何返回null而不是ErrorException - php

我正在编写一些Laravel Blade模板,并且我的模型可能包含空对象。我非常想尝试获取对象属性,如果有错误,则返回null。因此,不必编写以下代码:@if ($model->child_object_that_may_be_null) {{ $model->child_object_that_may_be_null->interesti…

Laravel-foreach局部变量正在覆盖全局变量 - php

今天,我面临一个非常奇怪的问题。我有一个控制器,将从该控制器向视图sections thread和threads发送三个变量。在我看来,我正在使用foreach循环遍历所有部分,如下所示:@foreach($sections as $i => $section) 对于每个部分,我都将创建一个div并给出如下的ID:id="{{ $thread…