April 21, 2018 —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$this->validate($request, [2 'username' => 'required|max:200',3 'secret' => 'required'4]);
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:
{lang="html",line-numbers=on}
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 APIThe 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:
1use Illuminate\Support\ViewErrorBag;2 3// Create a new ViewErrorBag instance.4$viewErrorBag = new ViewErrorBag;5 6// Determine if the default MessageBag7// instance is empty, which in this case8// is true.9$viewErrorBag->isEmpty();
∎
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.