For the most part, I don’t have many complaints when it comes to Laravel. That being said, every now and then I find myself trying to accomplish something I’d consider to be relatively simple only to keep hitting brick walls.
As handy as it is for the Laravel Validator to automatically generate friendly error messages (turning ‘address_line_1’ into ‘address line 1’ and what such) it doesn’t always give me what I’d like. While I’m sure most people would eventually be able to figure out why on earth a web application keeps telling them that their ‘promo starts at’ field must be before the ‘promo ends at’ field, something in my head told me that it was probably worth spending another 60 seconds of development time on simply renaming these fields in the big shouty error messages so that they at least matched the labels beside each input?
The weird thing is, Laravel only documents doing this in a way that forces you to write every validation message for every validation rule without a way of simply renaming a field. What the…? That feels like more work than it really should be for something so trivial…
And that’s just it — rewriting every validation message just isn’t necessary. Although it’s not documented anywhere (that I can find anyway) there is an additional parameter you can pass to Validator::make that achieves exactly what I was after. You simply give it an associative array of ‘field_name’ to ‘friendly name’ and everything else falls into place!
$attrs = [
'promo_starts_at' => 'promotion start date’,
'promo_ends_at' => 'promotion end date'
];$validator = Validator::make($request->all, $rules, , $attrs)
Here Laravel will use all of the default messages for every field but be kind enough to replace our rather ugly field names with something more appropriate!