Change laravel error attributes to more reader friendly

Change laravel error attributes to more reader friendly

Swap error attributes to more reader friendly. For example, "Item code" instead of "item_code".

Fazail Alam
Frontend dev · Sat Jul 02 2022

There are many built-in error messages that include an :attribute placeholder that is replaced with name of the field or attribute under validation. You can customize them as you like in the lang/en/validation.php file. en is default language that ships with laravel you can add more languages in that directory.

Lets imagine you build an laravel dashboard and every thing is working smoothly. But when a validation error occurs, a message is shown The invoice_number field is required. This is can be a bad user experience which you don’t want. And to change that may be on blade file you replace invoice_number with Invoice Number. But this will not change on all the pages. And to solve this problem laravel provides attributes array where you can define which field name to replace with what value.

Attributes

lang/en/validation.php

	'attributes' => [
		'invoice_number' => 'Invoice Number',
	],

This will replace invoice_number to Invoice Number on all the pages whenever error occurs.

Nested attributes

For nested fields you can define it dot notation like invoice.tax.

InvoiceController.php
	$invoice->tax 

	// /lang/en/validation.php
	'attributes' => [
		'invoice.tax' => 'Tax',
	],

Sometime you need to validate inside loops, which can give you field attribute like invoice_items.0.name.

InvoiceController.php
	$invoice_items[0]->name
lang/en/validation.php
	'attributes' => [
		'invoice_items.*.name' => 'Item Name',
	],

Want frameworks news and updates?

Sign up for our newsletter to stay up to date.

Share on: