Intermediate LevelLaravel
How do you create Custom Invokable Validation Rules in Laravel?
❓ Interview Prompt: Explain custom validation rules (php artisan make:rule), ValidationRule interface, __invoke(attribute, value, fail) method.
Creating custom validation rules via 'php artisan make:rule Uppercase' generates a clean invokable class implementing 'ValidationRule':
Structure:
Implement '__invoke($attribute, $value, $fail)'. If validation fails, invoke '$fail("The :attribute must be uppercase.")'.
Code Implementation Example
php
<?php
namespace AppRules;
use Closure;
use IlluminateContractsValidationValidationRule;
class Uppercase implements ValidationRule
{
public function __invoke(string $attribute, mixed $value, Closure $fail): void {
if (strtoupper($value) !== $value) {
$fail('The :attribute must be uppercase.');
}
}
}💡Custom invokable validation rule implementing ValidationRule interface.
🎯 Interview Key Takeaway
Create invokable custom validation rules (ValidationRule) for complex domain input validation.
#Validation Rules#Invokable#Custom Rules#Intermediate
Back to all Laravel Questions→