Search code examples
laravelvalidation

In Laravel, how can I get the validation errors


I am getting the web method just thrown out, and rest of the code after the line (see code below) doesn't run. With this code, I cannot seem to get where the error is, even though I can see that the Laravel has issues with the email being unique. I only have handful of users, and all of them have different emails. I can see that in the DB. This is the code, in any case:

$validatedData = $request->validate([
            'email' => 'required|email|unique:users',
            'password' => 'nullable|min:6',
            'name' => 'nullable|string|max:255',
            'about_me' => 'nullable|string|max:300',
        ]);

if I omit the part |unique:users the code runs fine i.e. it gets past the $validatedData=.... line. Why is Laravel making this mistake? The email is indeed unique, I see it clearly in the DB for the 10 or so users that I have. I want to see what errors is Laravel catching, and also, because I assume it is catching the email error, the email being not unique (which is not true, the email is unique), why is he doing this?


Solution

  • Is this happening when you are updating the record? If yes then while updating the record you will have to ignore the current user's ID from the unique check.

    $validatedData = $request->validate([
                        'email' => 'required|email|unique:users,email,'.$id,
                        'password' => 'nullable|min:6',
                        'name' => 'nullable|string|max:255',
                        'about_me' => 'nullable|string|max:300',
                    ]);
    

    OR

    $validatedData = $request->validate([
                        'email' => ['required','email',Rule::unique('users')->ignore($id)],
                        'password' => 'nullable|min:6',
                        'name' => 'nullable|string|max:255',
                        'about_me' => 'nullable|string|max:300',
                    ]);
    

    Please check validation