Laravel request validation in API

Viewed 34

I'm doing my first steps in Laravel. I would like to code an API with register function. In my AuthController I have the following function:

    public function register(Request $request)
{
    $validatedData =          $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:6',
    ]);

    $user = User::create(['name' => $validatedData['name'], 'email' => $validatedData['email'], 'password' => Hash::make($validatedData['password']) , ]);

    $token = $user->createToken('auth_token')->plainTextToken;

    return response()
        ->json(['access_token' => $token, 'token_type' => 'Bearer', ]);
}

Everything works fine, but when I'm entering an email which is already registered, then I'm redirected to the public welcome to Laravel page. I think, that the problem is caused by the validation. So my question is: how can I code it, that the API shows json error message? Thanks!

0 Answers
Related