Displaying the Error Messages in Laravel after being Redirected from controller
Laravel 4
When the validation fails return back with the validation errors.
if($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
You can catch the error on your view using
@if($errors->any())
{{ implode('', $errors->all('<div>:message</div>')) }}
@endif
UPDATE
To display error under each field you can do like this.
<input type="text" name="firstname">
@if($errors->has('firstname'))
<div class="error">{{ $errors->first('firstname') }}</div>
@endif
For better display style with css.
You can refer to the docs here.
UPDATE 2
To display all errors at once
@if($errors->any())
{!! implode('', $errors->all('<div>:message</div>')) !!}
@endif
To display error under each field.
@error('firstname')
<div class="error">{{ $message }}</div>
@enderror
If you want to load the view from the same controller you are on:
if ($validator->fails()) {
return self::index($request)->withErrors($validator->errors());
}
And if you want to quickly display all errors but have a bit more control:
@if ($errors->any())
@foreach ($errors->all() as $error)
<div>{{$error}}</div>
@endforeach
@endif
@if ($errors->has('category'))
<span class="error">{{ $errors->first('category') }}</span>
@endif
A New Laravel Blade Error Directive comes to Laravel 5.8.13
// Before
@if ($errors->has('email'))
<span>{{ $errors->first('email') }}</span>
@endif
// After:
@error('email')
<span>{{ $message }}</span>
@enderror
to Make it look nice you can use little bootstrap help
@if(count($errors) > 0 )
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<ul class="p-0 m-0" style="list-style: none;">
@foreach($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif