Complex Conditional Validation

Mar 22, 2024

I was working on a project where I needed to validate attributes under a special condition. Laravel already ships with some conditional validations, such as required_if and required_with. Still, these validations operate only with form fields, which is not my goal, so after a few hours of searching, I found a way to define the below method in the Form Request class:

 

use App\Models\User;

/**
 * Get the validator instance for the request.
 *
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function getValidatorInstance()
{
    $validator = parent::getValidatorInstance();

    return $validator->sometimes('password', 'required|string|max:30', function () {
        return auth()->user() instanceof User;
    });
}

 

The `sometimes` method accepts three arguments: the attribute you want to validate, the validation rules (as a string or an array), and a closure that returns a boolean value determining whether the validation should be applied.

AI Assistant

Summarize, simplify, and ask questions about this content using your preferred AI provider.

Text Tools

Generate cleaner and easier-to-read versions of this content instantly

Have a Question?

Ask anything related to this content and get a focused AI-generated answer.

0/500
Mahmoud Ramadan
Author

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.