How to display/show validation error in Laravel blade

In this tutorials of Laravel, we are going to tell you how to show validation error in Laravel blade file.

Blade files are the frontend part that views relevant information and data to a user. We can also pop up error messages in a blade file. Corresponding success or error messages to any user activity can pop up in the blade files. Let’s go through the explanation below.

In the code example below, we are validating error messages, sessions with success and error. If we have values set, we can display the message on the front end.

@if($errors->any())
    <div class="alert alert-danger">
        <p><strong>Opps Something went wrong</strong></p>
        <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
        </ul>
    </div>
@endif

@if(session('success'))
    <div class="alert alert-success">{{session('success')}}</div>
@endif

@if(session('error'))
    <div class="alert alert-danger">{{session('error')}}</div>
@endif

The code snippet below displays errors in Laravel. If an error comes up and we have a value set, we will display it on the front end.

@if(count($errors) > 0)
<div class="p-1">
    @foreach($errors->all() as $error)
    <div class="alert alert-warning alert-danger fade show" role="alert">{{$error}} <button type="button" class="close"
            data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
        </button></div>
    @endforeach
</div>
@endif

Following code snippet will show validation error, whatever is set on $errors array. The implode function displays messages from the $errors array. The array allows both, single and multiple errors to be displayed.

@if($errors->any())
    {{ implode('', $errors->all('<div>:message</div>')) }}
@endif

In case we want to validate a form element. Lets say, the first name, we will validate it as shown below to display the corresponding error.

<input type="text" name="firstname">
@if($errors->has('firstname'))
    <div class="error">{{ $errors->first('firstname') }}</div>
@endif

Hope the explanation helped you understand how to view error messages in a blade or view file of Laravel applications.

Leave a Comment