Nice attribute names for Laravel form validation messages

Laravel has strong support for server side form validations. It comes with a number of classes to support validating input data against a rich set of validation rules. Every validation rule has a message which lets you know when that particular rule is failed. For example:


namespace App\Http\Controllers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class PageController extends Model
    public function store(Request $request)
        $this->validate($request, [
            'title' => 'required|string',
            'bg_img' => 'required|file',

        // create new page

When title parameter is not filled in your request data, first validation rule throws the error.

The title field is required.

This looks OK. But what about the error message you see when the validation rules failed for bg_img field?

The bg img field is required.

That doesn’t really look good. I would be much better if it said:

The background image field is required.

Don’t worry, Laravel provides a way to handle this.

Language files to save you

Laravel uses translation files for supporting multiple languages. Due to this reason, it comes with a set of files to cover the default language, which is English. You can find these files at path resources\lang\en. You may also notice that there is a separate file for validations, validation.php

Laravel language files

Open it to find the attributes array towards the bottom of the file. You can add nice names for all of your attributes here. Since we have only one ugly name right now, I will add a nice name for it.

| Custom Validation Attributes
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.

'attributes' => [
    'bg_img' => 'Background Image',

That’s all. Now if you check the error message, it would say:

The Background Image field is required.

Saranga A web developer and highly passionate about research and development of web technologies around PHP, HTML, JavaScript and CSS.
comments powered by Disqus