Reputation: 324
I want to keep nullable and should be unique on My validation. Here is my code. can you please help me with this in controller
$this->validate($request, [
'class_teacher' => 'unique:sections',
]);
in migration
public function up()
{
Schema::create('sections', function (Blueprint $table) {
...
$table->bigInteger('class_teacher')->unsigned()->nullable();
...
$table->foreign('class_teacher')->references('id')->on('teachers');
});
}
in 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>
here class_teacher is the foreign key from teachers table. but I want to keep nullable and unique Also for class teacher. but now In validate. it always sent errors. that The class teacher has already been taken.
can anyone help me to keep this validation that keep it unique and also nullable? please?
Upvotes: 0
Views: 1462
Reputation: 1769
Change your validation rule this way
$this->validate($request, [
'class_teacher' => 'sometimes|nullable|unique:sections',
]);
Upvotes: 1