Home > Net >  How to handle Laravel Validator Exist default function when it fails
How to handle Laravel Validator Exist default function when it fails

Time:11-15

Background

So I have a validator:

  1. To determine whether an email format is correct or not
  2. Does the email already exist in the database
  3. Along with some other column validation (just ignore this) Like this:
$validator = Validator::make($request->all(), [
    'name' => 'required|string|max:255',
    'email' => 'required|string|email|max:255|unique:MyTable,email',
    'mobile' => ['required', 'regex:/^(62)8[1-9][0-9]{6,9}$/'], // Valid: 6281234567890
    'birthdate' => 'required|date',
    'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->numbers()],
    'allow_received_information' => 'integer',
]);

Error messages will be displayed one by one if there is an error in the input form with this code:

if ($validator->stopOnFirstFailure()->fails()) {
    return ResponseFormatter::error(null, implode(",", $validator->messages()->all()));
}

Question

So my question is, how to catch the event if an email already exists in the database or not among other validations? Maybe it's as simple as this:

if ('email' == alreadyExistFunc()) {
    # if already exist in db
} else {
    # if not
}

Trial 1

I found some functionality from Laravel's After Validation Hook, but I don't know if this is the exact function I need, and I don't know how to use it either..

$validator = Validator::make();
 
$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add(
            'field', 'Something is wrong with this field!'
        );
    }
});
 
if ($validator->fails()) {
    //
}

Trial 2

I could just remove the email validation 'email' => 'required|string|email|max:255|unique:MyTable,email' from the rule code line, and do it manually like this:

$isExist = MyTable::where('email', $request->email)->first();

if ($isExist != null) {
    # code...
} else {
    # code...
}

But is it best practice?
I think there is a way automatically..

Please for suggestions or answers, thank you

CodePudding user response:

$validator = Validator::make($request->all(), [
    'email' => 'required|unique:MyTable,email|string|email|max:255',
    'name' => 'required|string|max:255',
]);

here's a list of methods available for your $error message bag in Laravel API: https://laravel.com/api/master/Illuminate/Contracts/Support/MessageBag.html

You can get a list of all error keys with:

$error->keys()

Or errors list with:

$errors->all()

Or a specific error by its key with:

$error->get('email')

CodePudding user response:

So thanks to the answer mentioned by Pouria Jahedi's answer, and through this reference, we can do logical conditioning like this:

if ($validator->fails()) {
     $errors = $validator->errors();
     if ($errors->first('email')) {
         return $errors->first('email');
     } else {
         return ResponseFormatter::error(null, implode(", ", $errors->all()));
     }
}
  • Related