Struggling to handle the AuthenticationException in Laravel 11

97 Views Asked by At

I'm trying to adapt some code from Laravel 10 to Laravel 11. The code customizes the error message when a user is not logged in. However, it's currently redirecting me to the login route, which I don't have declared because I'm working with an API.

The code I'm using is located in the bootstrap folder:

$exceptions->stopIgnoring(AuthenticationException::class);
$exceptions->render(function (Request $request, AuthenticationException $exceptions) {
    return $request->expectsJson()
        ? response()->json(['message' => $exceptions->getMessage()], 401)
        : response()->json(['message' => __('User does not have authenticated'), 'error' => $exceptions->getMessage()], 401);
});

But it's not working as expected. I want to modify the default response that Laravel 11 provides for AuthenticationException.

0

There are 0 best solutions below