Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

id2002's avatar

Struggling to handle the AuthenticationException in Laravel 11

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 in the section withExceptions:

 $exceptions->stopIgnoring(AuthenticationException::class);

    $exceptions->render(function (AuthenticationException $exceptions, Request $request) {
        dd($exceptions);
        return $request->expectsJson()
        ? response()->json(['message' => $exceptions->getMessage()], 401)
        : response()->json(['message' => __('You are not logged in'), 'error' => $exceptions->getMessage() ], 401);

    });

But it's not working as expected. My current configuration is: "require": { "php": "^8.2", "laravel/framework": "^11.0", "laravel/sanctum": "^4.0", "laravel/tinker": "^2.9", "spatie/laravel-activitylog": "^4.8", "spatie/laravel-permission": "^6.4", "yajra/laravel-datatables": "^11.0" }, "require-dev": { "fakerphp/faker": "^1.23", "laravel/pint": "^1.13", "laravel/sail": "^1.26", "mockery/mockery": "^1.6", "nunomaduro/collision": "^8.0", "phpunit/phpunit": "^10.5", "spatie/laravel-ignition": "^2.4" },

0 likes
5 replies
Snapey's avatar

don't understand why anything would change with authentication between 10 and 11. Your old code should work fine.

id2002's avatar

@Snapey That is the problem. Before, I handled that issue with the handler and it had an extra function, but now that structure has been changed.

id2002's avatar

Apparently it doesn't recognize the name AuthenticationException , because I worked this and it did work:

$exceptions->render(function (UnauthorizedException $exceptions, Request $request) {

        return $request->expectsJson()
        ? response()->json(['message' => $exceptions->getMessage()], 401)
        : response()->json(['message' => __('User does not have the right permissions'), 'error' => $exceptions->getMessage() ], 401);

    });

but I still can't handle the error when you are not logged in

id2002's avatar

I was checking thoroughly and the problem seems to be that I do not have the route Route[login] defined, the error is overwritten with the RouteNotFoundException and the latter is that it is registered... how could I rewrite the authenticated method of Laravel so that this does not happen?

id2002's avatar
id2002
OP
Best Answer
Level 1

I just saw and I only had to create the login route, now I can get the error

Please or to participate in this conversation.