Write Your Laravel Validation Logic Like a Senior Dev, Part 2
Making custom rules when they get complicated

I am a full-stack web developer that enjoys coding in Laravel and React.
Search for a command to run...
Making custom rules when they get complicated

I am a full-stack web developer that enjoys coding in Laravel and React.
No comments yet. Be the first to comment.
Here I will post some articles that help devs with simple and complex topics in Laravel.
I've been gone for a while, but I'm back! During my 'break' I gave Inertia with Laravel another chance and ended up liking it. I'm still not a fan of how Laravel devs still have to go to multiple places for docs, but it's what we have so far until th...
Switching stacks

If you don't know what Twin Macro is, check it out! It's a great library that blends Tailwind CSS and Styled Component systems, like Emotion. I love using Twin because it lets me use Tailwind while separating my styling from my markup and methods. If...

Many developers know that full-stack apps with a Vue frontend can be quickly spun up with Laravel Jetstream. What many don’t know is that recently, the Laravel team made it easy to make an Inertia app with Laravel Breeze. In this article, we'll make ...

Extending the Rule Object with a DateTime Trait

Using Custom Console Commands

Sometimes the rules that come pre-built into Laravel are not enough. Luckily, Laravel provides a way for you to create your own rules using a separate Rule class. In this post, I'll show you how we can create a custom rule that makes sure passwords are at least 8 characters and includes a symbol, a number, and a lower and upper case letter.
Preliminaries:
php artisan serveThe Work Begins:
php artisan make:rule StrongPassword. passes() and message(). The passes() method will check to see if the $attribute's condition in terms of the $value is met and returns either true or false. The message() method returns whatever string you want to return when passes() is false.preg_match() to help with that.The Work Continues:
$attribute's $value to return a boolean:public function passes($attribute, $value)
{
return preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@()$%^&*=_{}[\]:;\"'|\\<>,.\/~`±§+-]).{8,30}$/", $value);
}
public function message()
{
return 'Your :attribute must be at least 8 characters and must include a number, a symbol, a lower and an upper case letter';
}
password is the attribute that we're making a rule for, it will replace :attribute in our string.The Work Ends:
StrongPassword. Now we need to instantiate it so we can use it. We'll replace the value for password in our rules() method and use an array instead.use App\Rules\StrongPassword;
...
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => ['required', 'string', new StrongPassword],
]
}

Conclusion: