Menü schliessen
Created: September 10th 2024
Last updated: September 27th 2024
Categories: Common Web Development,  Laravel
Author: Tim Fürer

Laravel: How to Define Validator Messages for Custom Rules

Tags:  Laravel,  PHP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Laravel allows you to define custom error messages for validation rules using key-value pairs where the key is the rule name and the value the custom message.

<?php

[
  'required' => 'foo is required.',
  'string' => 'foo must be a stirng.',
]

?>

While the names for built-in rules are obvious, it may not be as obvious for custom rules. The official Laravel documentation doesn't mention this anywhere, but you're supposed to use class strings.

<?php

[
  MyCustomRule::class => 'foo needs to abide my custom rule.',
]

?>

However, for anonymous custom rules (that use functions), there unfortunately doesn't seem to be an elegant way to define custom messages.