Before you go, check out these stories!

0
Hackernoon logoError Messages Vs Validation Messages in Laravel Blade by@marco_aurélio_deleu

Error Messages Vs Validation Messages in Laravel Blade

Author profile picture

@marco_aurélio_deleuMarco Aurélio Deleu

I like to show error messages on top of the page and it’s pretty easy to do that with Laravel and Blade:

@if(!empty($errors->first()))
    <div class="row col-lg-12">
        <div class="alert alert-danger">
            <span>{{ $errors->first() }}</span>
        </div>
    </div>
@endif

Whenever I redirect the user back with an error I know the page will be capable of showing the message properly at the top because of the base template.

However, if you do this and then setup a Form Validation, you’ll see only the first error message on top of the page. We could go through all messages in the errors variable, but it would still be showing form errors on top of the page instead of under each field. To prevent that, we can leverage Message Bags from Laravel Form Requests.

Setting your Validation messages on a separate Message Bag

1- Base Form Request

Create a

BaseFormRequest
and extend it from your
FormRequests
.

use Illuminate\Foundation\Http\FormRequest;
class BaseFormRequest extends FormRequest {

    protected $errorBag = 'form';

}

2- Setup a blade component for field messages

In here we use the attribute $errors->form to match the errorBag value set on Step 1. We also use a variable called field that will need to be set whenever using this component.

@if($errors->form->first($field))
    {!! $errors->form->first($field, '<p><span class="text-warning">:message</span></p>') !!}
@endif

3- Use the component under your fields

When declaring a field inside your form, make sure to include the component created on Step 2 and give it the field variable with the same name as your field/rule.

<div class="form-group">
    <label>{{ __('What is the subject of this ticket?') }}</label>
    <input type="text" name="title" class="form-control">
    @include('layouts.components.alert.field', ['field' => 'title'])
</div>

Conclusion

That’s it! Now, when the Form Request rule fails, it will set the Message Bag on form instead of default. Now we can easily return errors to be shown on top with withErrors() method as well as show per-field messages with Form Requests.

Tags

Become a Hackolyte

Level up your reading game by joining Hacker Noon now!