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

sarfaraz1212's avatar

Laravel 11 spatie forbidden exception

i am using laravel 11 and spatie the code works fine. i just need custom exception message as i am building api's

The current message is

   "message": "User does not have the right roles.",
    "exception": "Spatie\\Permission\\Exceptions\\UnauthorizedException",
    "file": "C:\\xampp\\htdocs\\SMS-API\\vendor\\spatie\\laravel-permission\\src\\Exceptions\\UnauthorizedException.php",
    "line": 22,

what i want is the following code to work

 return response()->json([
                'responseMessage' => 'You do not have the required authorization.',
                'responseStatus'  => 403,
            ]);

i have done the following so far but no success

    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->report(function (\Spatie\Permission\Exceptions\UnauthorizedException $e) {
            return response()->json([
                'responseMessage' => 'You do not have the required authorization.',
                'responseStatus'  => 403,
            ]);
        });
    })->create();
0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Use renderable method rather than report:

        $exceptions->renderable(function (\Spatie\Permission\Exceptions\UnauthorizedException $e) {
            return response()->json([
                'responseMessage' => 'You do not have the required authorization.',
                'responseStatus'  => 403,
            ]);
        });

Please or to participate in this conversation.