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.