Background
So I have a validator:
- To determine whether an email format is correct or not
- Does the email already exist in the database
- 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
2
Answers
So thanks to the answer mentioned by Pouria Jahedi's answer, and through this reference, we can do logical conditioning like this:
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:
Or errors list with:
Or a specific error by its key with: