5

I am creating API with sanctum, and works fine I can list users, update, store, etc.

I added middleware auth:sanctum and passing token, and I add middleware EnsureFrontendRequestsAreStateful like explained in docs.

With invalid token doesn't work and I am redirect to login.

However, issue happen when validation failed, I am using form request, but even with in controller validation, when fail then I am redirect to home.

I am using Postman for testing API and if I disable "Automatically follow redirects" I can see html page for redirect used by setTargetUrl, this:

<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='%1$s'" />

        <title>Redirecting to %1$s</title>
    </head>
    <body>
        Redirecting to <a href="%1$s">%1$s</a>.
    </body>
</html>

which point to my home.

I try to check from where is done this redirect, but can't understand. And is not by RedirectIfAuthenticated.

I expect to see a JSON response of with errors messages.

Even the example code of Laravel docs for create a token, if validation fail, there is this redirect, this code:

        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
            'device_name' => 'required',
        ]);

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        return $user->createToken($request->device_name)->plainTextToken;

And only when validation fail, but there is not a redirect, so I suppose validation do a redirect back but since there is not, it redirect to home.

Thanks

Update

I found a workaround but not sure if this is the only way.

Adding a try catch I can display validation errors without redirect.


    try {

        $data = $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required',
        ]);

    } catch(\Illuminate\Validation\ValidationException $e) {
        
        return response()->json([
            'message' => $e->getMessage()
        ]);
    }
Zoroaster
  • 63
  • 1
  • 7

1 Answers1

21

You would probably want to be sending the Accept header as application/json so that the server knows you are accepting JSON back. This is part of how the Exception Handler determines how to return a response from the validation exception.

lagbox
  • 48,571
  • 8
  • 72
  • 83
  • 2
    I had the same problem and this solution solved it for me. The problem is that in Postman the default for the `Accept` header is `*/*` so every type of response is accepted – Mavv3006 Dec 08 '20 at 15:45