Ways to display Errors in Laravel views

by Sam  

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')


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>
@if ($errors->has('lastname'))
<div class="error">{{ $errors->first('lastname') }}</div>

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>')) !!}

Your choice.

Which of these do you prefer? Please comment your answer below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Need of a Website?

Maybe you're planning to build a landing page for your website. You might also have a plan to create a web application. I can offer you with an affordable but with good quality services. Don't hesitate to submit your specifications by clicking the button below.

Get Quote