Laravel Service Container and Service Providers
Two concepts sit at the heart of every Laravel application: the service container and service providers. Once you understand them, a lot of Laravel's…
Laravel ships with a long list of validation rules, but sooner or later you need one that doesn't exist. In this article I'll show how I create custom validation rules in current Laravel versions, using rule objects and closures.
The cleanest way is a rule object. Artisan creates it for you:
php artisan make:rule Uppercase
This creates app/Rules/Uppercase.php. The class implements the ValidationRule interface, which has a single validate method.
Inside validate you check the value and call $fail with a message when it isn't valid:
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class Uppercase implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (strtoupper($value) !== $value) {
$fail('The :attribute must be uppercase.');
}
}
}
The :attribute placeholder is replaced with the field name, just like in Laravel's built-in messages.
Pass an instance of the class together with other rules:
use App\Rules\Uppercase;
$request->validate([
'name' => ['required', 'string', new Uppercase],
]);
It works the same way in a Form Request's rules() method.
If your rule needs configuration, accept it in the constructor:
class MaxWords implements ValidationRule
{
public function __construct(private int $max) {}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (str_word_count($value) > $this->max) {
$fail("The :attribute may not have more than {$this->max} words.");
}
}
}
'bio' => ['required', new MaxWords(50)],
Instead of a hard-coded string, you can pass a translation key and call translate():
$fail('validation.uppercase')->translate();
Then add the uppercase key to your lang/en/validation.php file. If the lang directory doesn't exist yet, publish it with php artisan lang:publish.
When a rule is only used once, a closure is enough:
$request->validate([
'title' => [
'required',
function (string $attribute, mixed $value, Closure $fail) {
if ($value === 'foo') {
$fail("The {$attribute} is invalid.");
}
},
],
]);
For anything reused across the app, I prefer a rule class: it's easier to test and keeps controllers clean.
By default, custom rules don't run when the field is missing or empty. If your rule must run even then, generate it with the --implicit flag:
php artisan make:rule Uppercase --implicit
Keep in mind an implicit rule only implies the field is required; whether it actually fails an empty value is up to your logic.
Two concepts sit at the heart of every Laravel application: the service container and service providers. Once you understand them, a lot of Laravel's…
No comments yet