Full-Stack Development

How to return errors in an error bag when using Laravel Form Requests.

When working with form submissions, it is nice to put validation rules in a separate class. Laravel has a nice feature that makes this easy to do, with Form Requests.

One problem that you may have when using form requests is when validating input for forms that are all on the same page. If you are using Inertia JS, or Axios to submit forms, then displaying errors based on the error bag returned, you may have validation errors displaying on forms that have not been submitted if they use the same input names.

A way to get around this issue is by using a feature of Laravel, called errorBags. Validations errors are returned in a "default" error bag out of the box, but you can place validations for separate forms in separate bags to prevent displaying errors in a form that hasn't been submitted.

Laravel shows in the docs how to do this with the Validator Class, but if you are using a form request, the validator is baked in, and it seems tricky to implement. Fortunately, Laravel provides a simple way to give your form request a named error bag out of the box.

In order to give your validation rules a named error bag from a form request, you only need to add the errorBag property to the Form Request.

Here is an example of what you need to do:

<?php

namespace App\Http\Requests;

use App\Models\Customer;
use Illuminate\Foundation\Http\FormRequest;

class StoreCustomerRequest extends FormRequest
{
    protected $errorBag = "createCustomer";
    
   // The rest of your form request
}

For the above example, requests being made through the StoreCustomerRequest will be validated and errors made into the createCustomer error bag. This makes it easy to use the errorBag on the front end while preventing the errors to be displayed in other forms.

Inertia JS provides an example of using the errorBag in their docs:

Inertia.post('/companies', data, {
  errorBag: 'createCompany',
})

Now this forms errors will be displayed from this named errorBag!

Chris Wray website logo

Trying to do my part in making the world a better place.

This site is hosted for free, so I am thanking the services I am using by adding a link to their websites here in the footer.

© 2020 Chris Wray. All rights reserved.