I have a select input on my form and when the user does not select a value I want to show an error. For some reason the error is not showing, although almost the same code does on another form.
The code that is working:
<div class="form-group row">
<label class="md-col-4 col-form-label text-md-right" for="slesson-date">Datum</label>
<div class="col-md-6">
<input id="slesson-date" class="form-control @error('date') is-invalid @enderror" type="date" name="date" required value="{{old('date', date('Y-m-d'))}}">
@error('date')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
The code that is not working:
<div>
<select name="code" class="selectpicker form-control" data-live-search="true" data-live-search-normalize="true" data-style="btn-secondary" title="Zoek een leerling">
@foreach($students as $student)
<option value={{$student->code}}>{{$student->name}}</option>
@endforeach
</select>
@error('code')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
Both input fields are validated using formrequests.
When I show all the errors on the end of the view the error is show so it is available, just not recognized by the @error('code')
for some reason.
Edit: I added the controllercode as per request.
public function sLessonsStudent(ValidateSLessonStudent $request)
{
$validated = $request->validated();
$code = $validated['code'];
$sLessons= SLesson::whereHas('studentProperty',function($query) use ($code){
$query->where('user_code',$code);
})->select('date','hour','classroom_number')->oldest('date')->orderBy('hour')->get();
$user = User::where('code',$code)->first();
$sLessonsJson = $sLessons->toJson();
return view('sAdmin.sLessonsStudent',compact('sLessonsJson','user'));
}
And the formrequest validating the request:
class ValidateSLessonStudent extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'code'=>['required']
];
}
/**
* {@inheritDoc}
* @see \Illuminate\Foundation\Http\FormRequest::messages()
*/
public function messages()
{
return [
'code.required'=>'Er moet een leerling gekozen worden!'
];
}
}
Update 2: The error is in the ErrorBag
ViewErrorBag {#438
#bags: array:1 [
"default" => MessageBag {#439
#messages: array:1 [
"code" => array:1 [
0 => "Er moet een leerling gekozen worden!"
]
]
#format: ":message"
}
]
}
After a long time of trial and error I found the problem.
The class "invalid-feedback"
in the following code
@error('code')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
needs to preceded with a form control with form-control @error('code') is-invalid @enderror"
. This is true for the working code where the input
has the required classes, but not for the second code where the select
has only the class form-control
and not the addition @error
directive.