Welcome to this tutorial on creating and implementing custom validation rules in Laravel. Our goal is to explore various scenarios that require more than the built-in validation rules in Laravel and how to handle them.
What You'll Learn
- How to create custom validation rules in Laravel
- How to implement these rules in your application
Prerequisites
- A basic understanding of PHP and Laravel
- Laravel installed on your local machine
Validation in Laravel is essential to ensure that the correct data type is being sent to your database. Laravel provides a variety of built-in validation rules, but sometimes you may need to specify some custom ones.
You can create a custom validation rule using the make:rule
Artisan command:
php artisan make:rule YourCustomRule
This command will create a rule object in your app/Rules
directory.
To use this custom rule, you will pass it to your validator in the form of an object:
$request->validate([
'field' => [new YourCustomRule],
]);
Let's create a custom rule that validates that a string is exactly 5 characters long.
php artisan make:rule FiveCharactersLong
In the app/Rules/FiveCharactersLong.php
file:
public function passes($attribute, $value)
{
return strlen($value) === 5;
}
$request->validate([
'username' => [new FiveCharactersLong],
]);
In this tutorial, we've learned how to create and implement custom validation rules in Laravel. You now know how to create a rule using the make:rule
artisan command, define the rule in your app, and implement it in your code.
Experiment with creating different custom validation rules. Try creating a rule that validates if a number is prime or if a string is a palindrome.
Exercise 1: Create a custom validation rule that checks if a number is even.
Exercise 2: Create a custom validation rule that checks if a string contains only alphabets and spaces.
Exercise 3: Implement the custom rules you created in exercises 1 and 2 in a form.
public function passes($attribute, $value)
{
return $value % 2 == 0;
}
public function passes($attribute, $value)
{
return preg_match('/^[A-Za-z ]*$/', $value);
}
Remember to keep practicing and experimenting with different rules. The more you practice, the better you will understand how to implement and use custom validation rules in Laravel.