COMPLEX CONDITIONAL VALIDATION

Mar 21, 2024 Copy Link

I was working on a project where I needed to fulfill validation on 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 so, after a few hours of searching I found a way to attain my goal which is defining 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;
    });
}

Share via

Filed in:

Tips Validation
Mahmoud Ramadan

Mahmoud Ramadan

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

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE