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