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.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js