David David - 4 months ago 63
PHP Question

Loop through validation errors, and display the right one - Laravel 5.2

I have a registration system, and I need to display any validation errors that come up. Most of my validation is being checked by JavaScript because I'm using the Semantic-UI Framework. But there is 2 custom validation rules that I cant really display in the JavaScript, so I need to see which of those two error messages it is, and flash the correct error message.

Here is my Register function with the validation:

public function postRegister (Request $request) {

$validator = Validator::make($request->all(), [
'username' => 'unique:users',
'email' => 'unique:users',
'password' => '',
]);

if ($validator->fails()) {
flash()->error('Error', 'Either your username or email is already take. Please choose a different one.');
return back();
}

// Create the user in the Database.
User::create([
'email' => $request->input('email'),
'username' => $request->input('username'),
'password' => bcrypt($request->input('password')),
'verified' => 0,
]);

// Flash a info message saying you need to confirm your email.
flash()->overlay('Info', 'You have successfully registered. Please confirm your email address in your inbox.');

return redirect()->back();


As you can see there are two custom error messages, and If a user gets just one of them wrong, it will flash my Sweet-alert modal with that message.

How can I maybe loop through my error message and see which one I get wrong, and display a specific flash message to that error?

Answer

To retrieve an array of all validator errors, you can use the errors method:

$messages = $validator->errors();
//Determining If Messages Exist For A Field
if ($messages->has('username')) {
    //Show custom message
}
if ($messages->has('email')) {
    //Show custom message
}