How to return 403 response in JSON format in Laravel 5.2?

As for the latest version of Laravel, as of now version >=7.x,

Generally setting request headers 'Accept' => 'application/json' will tell Laravel that you expect a json response back.

For errors you need to also turn off debugging by setting the APP_DEBUG=false on your .env file, which will make sure the response is json and no stacktrace is provided.


We managed to resolve this by modifying the exceptions handler found in App\Exceptions\Handler.php adding it in the render function.

public function render($request, Exception $e)
{
    if ($e instanceof AuthorizationException)
    {
        return response()->json(['error' => 'Not authorized.'],403);
    }
    return parent::render($request, $e);
}

You can intercept the exception

    try {
        $this->authorize('update', $data);
    } catch (\Exception $e)
    {
        return response()->json(null, 403);
    }

Yes, make a simple before method in your policy which will be executed prior to all other authorization checks,

public function before($user, $ability,Request $request)
{
    if (!yourconditiontrue) {
         if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return abort('403');
        }
    }
}