Laravel/PHP Articles

Articles from Laravel/PHP sites on the web

Laravel/PHP Articles
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.

Sign Up For Our Newsletter

Each Week, We curate the top Laravel/PHP articles, jobs, events and More!

We'll send you a weekly email with the latest Laravel/PHP articles, jobs and events. Please review our Code of Conduct in the meantime. Talk to you soon!