Category: Laravel

Laravel validation system is great, including auto-populating error messages.
But what if you want to override the names of the :attribute parameter values?
Typical example of validation rules array:$rules = [ 'first_name' => 'required', 'last_name' => 'required', ];Then, if validaton fails with first_name being empty, automatic error message will say this: The first name field is required.
Here’s an example with Validator class:$rules = [ 'first_name' => 'required|bail', 'last_name' => 'required', ]; $messages = [ 'required' => 'please specify :attribute option', ]; $attributes = [ 'first_name' => 'first_name', 'last_name' => 'last_name', ]; $validator = Validator::make($request->all(), $rules, $messages, $attributes);Look at that $attributes array, and we’re passing it as the 4th parameter to Validator::make().
If you are using FormRequest classes for validation, then all you need to do is add method attributes() to the class, with the same values:public function attributes() { return [ 'first_name' => 'first_name', 'last_name' => 'last_name', ]; }Read more about validation in official Laravel documentation.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Community Partners