Let’s assume that you have already made a form in your view and added a controller. Now, after the user submits the form, you’ll need to add a validation rule.
On this page, we’re going to show you how to display error messages in two ways. I have added a UserController below.
class UserController extends Controller
{
public function store(Request $request)
{
$validator = \Validator::make($request->all(), [
'firstname' => 'required|unique:posts|max:255',
'lastname' => 'required',
]);
if ($validator->fails()) {
return redirect('/home')
->withErrors($validator)
->withInput();
}
}
}
Solutions
Option 1. Display one error at a time
Displaying the error one at a time is just simple. Laravel uses has() method to check if validation fails for a specific field. Check an example below.
@if ($errors->has('firstname'))
<div class="error">{{ $errors->first('firstname') }}</div>
@endif
@if ($errors->has('lastname'))
<div class="error">{{ $errors->first('lastname') }}</div>
@endif
The advantage of using this option is to limit the number of errors to be displayed per validation. Also, you can fully control the position of error messages.
Option 2. Display all errors in minimal code.
The first option might be tiresome since you need to specify all fields to be displayed. Now, if you want to display all errors easily. You can use the code below.
@if ($errors->any())
<div class="alert alert-danger">
{!! implode('', $errors->all(':message <br>')) !!}
</div>
@endif
Your choice.
Which of these do you prefer? Please comment your answer below.