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

musa11971's avatar

Custom "This action is unauthorized." response

In my application, I'm using middleware to run my policies, like so:

Route::post('/{user}/profile', [UserController::class, 'updateProfile'])
    ->middleware('can:update_profile,user');

This is fine and the policy works as expected, however when the action is unauthorized, the following exception is thrown:

  "message": "This action is unauthorized.",
  "exception": "Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException",

I'd like to make a custom JSON response instead of this exception, how can I do this?

0 likes
2 replies
D9705996's avatar
D9705996
Best Answer
Level 51

You could modify the render method in app/Exception/Handler.php

public function render($request, Exception $exception)
{
    if ($exception instanceof AccessDeniedException) {
        return response()->json([
         'message' => 'your error message'
        ],401);
    }

    return parent::render($request, $exception);
}

Think I've got the response syntax correct from memory but you might need to check the docs

2 likes
med-ezzairi's avatar

For Laravel version 8.* we could redefine the failedAuthorization() function in the FormRequest to throw a specific exception:

//App\Http\Requests\AppGenericRequest.php
class AppGenericRequest extends FormRequest {
    ...
    /**
     * Handle a failed authorization attempt.
     *
     * @return void
     *
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    protected function failedAuthorization()
    {
        throw new CustomAuthorizationException;
    }
}

And

//App\Exceptions\CustomAuthorizationException.php
namespace App\Exceptions;


use Illuminate\Auth\Access\AuthorizationException as ParentAuthorizationException;

class AuthorizationException extends ParentAuthorizationException
{
    
    public function render($request)
    {
        return response()->json(['message' => "your message"] );
    }
}

Please or to participate in this conversation.