Show Laravel error message in Blade

0
15543
Show Laravel error message in Blade
Show Laravel error message in Blade

When rendering data into Laravel Blade template, sometimes you will need to show error message into views. This is a fairly simple guide on how to show Laravel error message via Blade template.

Show Laravel error message

By default in Laravel, the $errors variable is a global one, which is bound automatically into all views, and you can access it directly in views without doing anything.

Assume you have following form error handling user interface.

<h1>Add new article</h1>

<form action="POST">
    <label for="title">Title</label>
    <input type="text" name="title" id="title">
    <p class="error"></p>

    <label for="content">Content</label>
    <textarea name="content" id="content" cols="30" rows="10"></textarea>
    <p class="error"></p>
    
    <button type="submit">Add article</button>
</form>

There are something to consider here.

  • First, you want to know if there is any error happening during view rendering.
  • Secondly, you don’t want to show that empty p.error tag if there is no error at all.

Check if there is any error

There are several methods you can try to check if there is any error in Laravel Blade templates.

$errors->any()
$errors->has()
$errors->count() > 0
$errors->isEmpty()

You can you any of those, also you can check for a error message for a specific key using has($key) such as:

@if ($errors->has('title'))
    <p class="error">{{ $errors->get('title') }}</p>
@endif

To get error message for a key, use get($key) method.

In some cases, a key can contain more than one message, and you only want to display the first message, then you will use $errors->first($key) to retrieve only the first one.

You can also use that to add conditional CSS error class for input field if necessary.

<input class="{{ $errors->has('title') ? 'error' : '' }}" name="title" />

So the CSS class error only displays if there is any error message associate with key title.

Show all Laravel error messages

You might also want to iterate and show all error messages at once, try following snippet:

@if($errors->has())
   @foreach ($errors->all() as $error)
      <div>{{ $error }}</div>
  @endforeach
@endif

Using Blade @error directive (Laravel 6+)

Show Laravel error message is a common task, so a new built-in Blade directive has been integrated into the framework, @error, starting from Laravel 6+ onward.

Usage for @error directive is straight-forward.

<input class="@error('title') error @enderror" name="title">
@error('title')
    <p class="error">{{ $errors->get('title') }}</div>
@enderror

Conclusion

Handling errors is fairly simple in Laravel and developers can easily show Laravel error message in Blade. Also, make sure to check Laravel official documentation for any future update.

Some references about how Laravel handles error message in Blade template: