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;
});
}