Laravel - JSON - Failed Authorization Returns HTML Instead of JSON

ISSUE:

JSON requests to backend that fail middleware checks return HTML page vs JSON Object

;TLDR:

Within each middleware check created, add a JSON check for the request, and included the appropriate message as well as the status code.

DETAILS:

I am in the process of changing the CRUD operations of my template to Vue/axios instead of old school page posts to a backend controller. 

Prior to this change, I was using a combination of middleware to verify access to the controller, and individual policies for each of the commands (Create,Read,Update,Delete).  For example, I may want a certain class of user to be able to view the resources, but only administrators can update the resource.  I grant both roles the "view-{modelName}" permission, where {modelName} is the actual model name of the resource (location, company, etc).  Then I grant the admin role the permission of 'edit-model', and use the policy of the resource to validate their access.

In changing over to a json POST, I'm now expecting a JSON response - which works great for successful submissions and validation errors.  However, I was finding that in my authorization tests that verify a specific user can not access a resource, I noticed that my JSON requests were always returning the HTML "Insufficient Privileges" page instead of the JSON version.

This is because the user verification was not passing my middleware permissions check. It was working as intended, but was only setup to return the HTML response and NOT JSON.

CODE:

App/Controllers/Middleware/CheckPermission.php:

public function handle($request, Closure $next, ...$permissions)
{
    $userRole = $request->user()->getSelectedRole();

    if ($userRole !== null) {
        foreach ($permissions as $permission) {
            if ($userRole->can($permission))
            {
                return $next($request);
            }
        }
    }
    // here is the change I added
    if ($request->expectsJson())
    {
        return response()->json(['success' => false,'message' =>"Sorry, you are not authorized"], 403);
    }

    return redirect('/insufficient-privileges');
}