Search code examples
laravellaravel-4ardentlaravel-validation

Custom attribute name in Ardent validation message


I'm using Ardent in my Laravel project because I love its awesome model validation feature. Now I need to set human understandable attribute values in the validation error messages. I read that it can be accomplished by setting the $attributes array in the validation.php file (lang folder).

Since I'm coming from Yii I wonder if there is a way to specify the attribute name on a model basis and not globally in validation.php lang file.

For example, if I have two models, Employee and Company, both with a "name" attribute, I would like to set the display value of "name" attribute to "Employee name" and "Company name" respectively.


Solution

  • Give this a try. It's from the documentation on GitHub. I've never worked with Ardent, but it actually has quite good writeups on it.

    class Employee extends \LaravelBook\Ardent\Ardent {
        public static $rules = array(
            'name' => 'Required|Alpha_Dash'
        );
        public static $customMessages = array(
            'required' => 'The Employee :attribute field is required.',
            'alpha_dash' => 'The Employee :attribute field must be Letters and Dashes only.'
        );
    }
    

    Since these custom messages are defined in the Employees class, they only apply to inputs from this class. You could do the same for the Company class:

    class Company extends \LaravelBook\Ardent\Ardent {
        public static $rules = array(
            'name' => 'Required|Alpha_Dash'
        );
        public static $customMessages = array(
            'required' => 'The Company :attribute field is required.',
            'alpha_dash' => 'The Company :attribute field must be Letters and Dashes only.'
        );
    }
    

    I think that should work. I don't have any way to test it however. The other option is using custom rules, such as

    'name' => 'Employee_Required|Employee_Aplha_Dash'
    

    And defining those in Laravel's validation. But anyway, I hope that helps!