Multiple forms with same input names on one page

Published on June 12th, 2019

Here's another tip! Even if it's documented here I just wanted to show it. Here's the deal: Imagine you have multiple forms on one page. For example one contact form and another newsletter signup form. Both of them might have an email field. So how do you know which email field doesn't validate and throws an error?

ErrorBags for the rescue

If you are using FormRequests, it's quite easy. You can set a custom ErrorBag on the specific FormRequest. Let me show you.

ContactFormRequest.php
<?php

use Illuminate\Foundation\Http\FormRequest;

class ContactFormRequest extends FormRequest
{
    protected $errorBag = 'contactForm';
}

NewsletterFormRequest.php
<?php

use Illuminate\Foundation\Http\FormRequest;

class NewsletterFormRequest extends FormRequest
{
    protected $errorBag = 'newsletterForm';
}

Earlier you have been used to use something like this in your blade files:

<div>{{ $errors->first('email') }}</div>

This uses the default ErrorBag. But in our case we have overwritten the bag with our custom ones. The syntax changes a little bit if you want access them. Here's how.

<div>{{ $errors->contactForm->first('email') }}</div>
<div>{{ $errors->newsletterForm->first('email') }}</div>

I hope this helps some of you.

Bobby Bouwmann and I are writing a book called "Laravel Secrets".
You will learn everything about the undocumented secrets of the popular Laravel framework. You can sign up using the form below to get early updates.
      Visit laravelsecrets.com to get more information.