Validation using closure

Submitted by asifzcpe - 2 months ago

If you only need the functionality of a custom 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:

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