Part #1: Closure-based Custom Laravel Validation

Harish Kumar · · 3706 Views

While I was working with Laravel, validation using closure came to my mind, and I know it will be helpful to you. This tutorial assists you with all what is the difference between closure-based validation and other validation methods. So, this article shows you how to use Laravel validating from request using closures.

If you only need the functionality of a custom validation rule once throughout your application, you may use a Closure instead of a rule object. The Closure receives the attribute's name, the attribute's value, and a $fail callback that should be called if validation fails. Below is the code example:

$request->validate([
    'new_password' => ['required', 'min:8', 'confirmed'],
    'new_password_confirmation' => ['required'],
    'current_password' => [
        'required',

        // closure-based Validation
        function ($attribute, $value, $fail) use ($user) {
            if (! Hash::check($value, $user->password)) {
                $fail("Invalid current password.");
            }
        }
    ]
]);
0

Please login or create new account to add your comment.

0 comments
You may also like:

Laravel Pint & VS Code: Automate Your Code Formatting

Laravel Pint is an opinionated PHP code style fixer built on top of PHP-CS-Fixer, designed to simplify the process of ensuring clean and consistent code style in Laravel projects. (...)
Harish Kumar

Laravel Clockwork: A Deep Dive into Debugging, Profiling Skills and Best Practices

In the world of web development, building complex applications often comes with the challenge of identifying and resolving performance bottlenecks. This is where a reliable debugging (...)
Harish Kumar

Effortless PDF Generation in Laravel: A Guide to Using Spatie/Browsershot Package

Looking to generate or export PDF files using Laravel? Look no further! In this article, we'll guide you through using the Laravel spatie/browsershot package to seamlessly convert (...)
Harish Kumar

Part #3: Rule objects based custom validation in Laravel

Laravel comes with multiple ways to add custom validation rules to validate form request inputs. I have already explained some of the ways in the following article links:
Harish Kumar

Part #2: How to use Laravel's Validator::extend method for custom validation

Validation is important in any application as it validates a form before performing actions on it. It allows the user to know their input is accurate and confident about the operation (...)
Harish Kumar

How to use the enumerations(Enums) of PHP 8.1 in Laravel?

The release of PHP 8.1 brings native enumerations to PHP. There is no more requirement for custom solutions in your Laravel projects since the Laravel v8.69 release has you back. (...)
Harish Kumar