QA
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→

More Laravel Interview Questions

Beginner LevelLaravel

How does the Laravel Service Container manage Dependency Injection and Bindings?

Beginner LevelLaravel

How does Routing work in Laravel including Named Routes and Route Parameters?

Beginner LevelLaravel

What is Blade Templating and how do custom directives work?