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

MohamedKamal's avatar

Auth Exception

i am building api with laravel and i am using spatie for roles and permission , the problem is that spatie when the user doesn't have the right role, the it return html page 403 not json message, what should i do?

0 likes
3 replies
Snapey's avatar

make sure your request says that it wants a json response.

ranto's avatar

There is a repo with laravel tips that shows how to force a json response by adding the header to incomming requests:

public function handle($request, Closure $next)
{
    $request->headers->set('Accept', 'application/json');
    return $next($request);
}

You can use something like this to all the api routes, so you don't get the HTML page error, just a json with the error.

Source to the tip: https://github.com/LaravelDaily/laravel-tips/blob/master/api.md#force-json-response-for-api-requests

Please or to participate in this conversation.