Search

An Introduction to Laravel View Error Bags

November 29, 2016 —John Koster

The Illuminate\Support\ViewErrorBag class is generally used to communicate error messages with views and responses. The ViewErrorBag itself is essentially a container for Illuminate\Contracts\Support\MessageBag implementation instances.

An instance of ViewErrorBag is shared with views if the current request contains any errors. This functionality is facilitated by the Illuminate\View\Middleware\ShareErrorsFromSession middleware. The ViewErrorBag instance that is shared with views is given the name errors. Interacting with the ViewErrorBag instance should look familiar to most developers:

1@if($errors->count())
2<div class="alert alert-danger">
3 <p>There were some errors that need to be fixed!</p>
4 <ul>
5 {!! implode($errors->all('<li>:message</li>')) !!}
6 </ul>
7</div>
8@endif

The following examples will assume that a form exists that asks a user for their username and a secret. The form will be validated from a controller using the following code sample (in this case there is no response when validation was successful):

1<?php
2 
3$this->validate($request, [
4 'username' => 'required|max:200',
5 'secret' => 'required'
6]);

If a user supplied only the username, the above Blade template code would generate the following HTML:

1<div class="alert alert-danger">
2 <p>There were some errors that need to be fixed!</p>
3 <ul>
4 <li>The secret field is required.</li>
5 </ul>
6</div>

If the user did not supply either a username or a secret, the following HTML code would have been generated:

1<div class="alert alert-danger">
2 <p>There were some errors that need to be fixed!</p>
3 <ul>
4 <li>The username field is required.</li>
5 <li>The secret field is required.</li>
6 </ul>
7</div>

#ViewErrorBag Public API

The ViewErrorBag exposes few methods itself in its public API (at the time of writing, only five methods exist intended for public use). However, the ViewErrorBag will redirect calls to methods that do not exist explicitly on the ViewErrorBag instance to the default MessageBag instance. Any public method that can be called on a MessageBag instance can be called on the default MessageBag instance without having to do any extra work:

1<?php
2 
3use Illuminate\Support\ViewErrorBag;
4 
5// Create a new ViewErrorBag instance.
6$viewErrorBag = new ViewErrorBag;
7 
8// Determine if the default MessageBag
9// instance is empty, which in this case
10// is true.
11$viewErrorBag->isEmpty();

The following articles detail each of the public API methods:

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.