Laravel Form Requests and Custom Error Messages

  • March 10, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Laravel 5's new form request feature helps you to keep actions responsible for processing submitted form data free of validation-related logic (if you're new to form requests see the post Creating a Contact Form in Laravel 5 Using the Form Request Feature). This feature is built atop Laravel's validation capabilities, meaning you can easily extend your form request to include custom validation messages. Read on to learn how.

The following form request is used in conjunction with a new developer community site I'm working on. Users can submit links to useful PHP sources, and I use the following form request to ensure the user submits a valid link name, URL, and associated category. You'll find the validation rules in the rules method. I additionally wanted to make the validation error messages more user-friendly. To do so you can add a method called messages, and associate each validation rule with a custom message, as I've done here:

class LinkCreateFormRequest extends Request {

    ...

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
          'name' => 'required',
          'url' => 'required|url',
          'category' => 'required|integer|min:1'
        ];
    }

    public function messages()
    {
        return [
            'name.required' => 'Please provide a brief link description',
            'url.required' => 'Please provide a URL',
            'url.url' => 'A valid URL is required',
            'category.required' => 'Please associate this link with a category',
            'category.min' => 'Please associate this link with a category'
        ];
    }

}

Notice how you can present multiple messages for a given form field, by concatenating the form field name with the specific validator. If for instance the url field value is not supplied, only the first message will render, meaning the reader won't be swamped with multiple messages pertaining to a specific field if several validators are chained together.