Laravel validation attributes "nice names"

Solution 1:

Yeahh, the "nice name" attributes as you called it was a real "issue" a few month ago. Hopefully this feature is now implemented and is very simply to use.

For simplicity i will split the two options to tackle this problem:

  1. Global Probably the more widespread. This approach is very well explained here but basically you need to edit the application/language/XX/validation.php validation file where XX is the language you will use for the validation.

    At the bottom you will see an attribute array; that will be your "nice name" attributes array. Following your example the final result will be something like this.

    'attributes' => array('first_name' => 'First Name')
    
  2. Locally This is what Taylor Otwell was talking about in the issue when he says:

    You may call setAttributeNames on a Validator instance now.

    That's perfectly valid and if you check the source code you will see

    public function setAttributeNames(array $attributes)
    {
        $this->customAttributes = $attributes;
    
        return $this;
    }
    

    So, to use this way see the following straightforward example:

    $niceNames = array(
        'first_name' => 'First Name'
    );
    
    $validator = Validator::make(Input::all(), $rules);
    $validator->setAttributeNames($niceNames); 
    

Resources

There is a really awesome repo on Github that have a lot of languages packages ready to go. Definitely you should check it out.

Hope this helps.

Solution 2:

The correct answer to this particular problem would be to go to your app/lang folder and edit the validation.php file at the bottom of the file there is an array called attributes:

/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/

'attributes' => array(
    'username' => 'The name of the user',
    'image_id' => 'The related image' // if it's a relation
),

So I believe this array was built to customise specifically these attribute names.

Solution 3:

Since Laravel 5.2 you could...

public function validForm(\Illuminate\Http\Request $request)
{
    $rules = [
        'first_name' => 'max:130'
    ];  
    $niceNames = [
        'first_name' => 'First Name'
    ]; 
    $this->validate($request, $rules, [], $niceNames);

    // correct validation