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 one page. For example one contact form and another newsletter signup form. Both of them might have an email field. So who 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.


use Illuminate\Foundation\Http\FormRequest;

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


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.

If you enjoy my articles or you like what I'am talking and twittering about, you should sign up. I will show you everything I know.
I send e-mails very irregularly. Your data is safe with me.