Backend Development
Laravel
Objective
Sep 30, 2025
How do you implement Custom validation rules in Laravel?
Detailed Explanation
Custom validation rules allow creating reusable validation logic:
**Creating Rule:**
php artisan make:rule Uppercase
**Rule Implementation (app/Rules/Uppercase.php):**
class Uppercase implements Rule {
public function passes($attribute, $value) {
return strtoupper($value) === $value;
}
public function message() {
return "The :attribute must be uppercase.";
}
}
**Using Custom Rule:**
use AppRulesUppercase;
public function store(Request $request) {
$request->validate([
"name" => ["required", new Uppercase],
"email" => "required|email",
]);
}
**Closure-based Rule:**
$request->validate([
"name" => [
"required",
function ($attribute, $value, $fail) {
if (strtoupper($value) !== $value) {
$fail("The $attribute must be uppercase.");
}
},
],
]);Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts