Nullable 和 Unique 不适用于 laravel 验证
Nullable and Unique is not working on laravel validation
我想保持可为空并且在我的验证中应该是唯一的。这是我的代码。你能帮我解决这个问题吗
在控制器中
$this->validate($request, [
'class_teacher' => 'unique:sections',
]);
迁移中
public function up()
{
Schema::create('sections', function (Blueprint $table) {
...
$table->bigInteger('class_teacher')->unsigned()->nullable();
...
$table->foreign('class_teacher')->references('id')->on('teachers');
});
}
在blade
<select class="select2" name="class_teacher" id="teacher">
<option value=""></option>
@foreach($teachers as $teacher)
<option value="{{ $teacher->id }}" {{ old('class_teacher') == $teacher->id ? 'selected' : '' }}>{{ $teacher->name }}</option>
@endforeach
</select>
这里class_teacher是老师table的外键。但我想为 class 老师保持可为空和唯一。但现在正在验证。它总是发送错误。 The class teacher has already been taken.
任何人都可以帮助我保持这种验证,使其保持唯一且可以为空吗?请问?
以这种方式更改您的验证规则
$this->validate($request, [
'class_teacher' => 'sometimes|nullable|unique:sections',
]);
我想保持可为空并且在我的验证中应该是唯一的。这是我的代码。你能帮我解决这个问题吗 在控制器中
$this->validate($request, [
'class_teacher' => 'unique:sections',
]);
迁移中
public function up()
{
Schema::create('sections', function (Blueprint $table) {
...
$table->bigInteger('class_teacher')->unsigned()->nullable();
...
$table->foreign('class_teacher')->references('id')->on('teachers');
});
}
在blade
<select class="select2" name="class_teacher" id="teacher">
<option value=""></option>
@foreach($teachers as $teacher)
<option value="{{ $teacher->id }}" {{ old('class_teacher') == $teacher->id ? 'selected' : '' }}>{{ $teacher->name }}</option>
@endforeach
</select>
这里class_teacher是老师table的外键。但我想为 class 老师保持可为空和唯一。但现在正在验证。它总是发送错误。 The class teacher has already been taken.
任何人都可以帮助我保持这种验证,使其保持唯一且可以为空吗?请问?
以这种方式更改您的验证规则
$this->validate($request, [
'class_teacher' => 'sometimes|nullable|unique:sections',
]);