Avoid Rule Object And Pass Closure To Validate Form Data In Laravel

Hello Artisan,

In this laravel advanced validation tutorial, i will discuss laravel custom validation rule with parameters. I will show you how we can validate our form requested data without rule using closure. 

I will validate requested data like a laravel custom rule object using closure. I think, this tutorial will help you to learn a new thing to validate your form data.

If we only need the functionality of a custom rule once throughout your application, we may use a Closure instead of a rule object.

This Closure receives the attribute's name, the attribute's value, and a $fail callback that should be called if validation fails. Let's see the example code of validation using closure.

$validator = Validator::make($request->all(), [
    'title' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if ($value === 'foo') {
                $fail($attribute.' is invalid.');
            }
        },
    ],
]);

 

Hope it can help you.

 

#laravel #laravel-8x #laravel-validation #laravel-tips