laravellaravel-8restlaravel-sanctum

Customize laravel sanctum unauthorize response


I am using laravel sanctum in my project, but I am facing a problem. I want to customize the 401 response code (unauthorized) to return a JSON when a token is invalid, something like this:

    {
    "data": {
        "code": 401,
        "book": null,
        "success": false,
        "error": {
            "message": "Not authenticated"
        }
    }
}

Instead of default response:

{
    "message": "Unauthenticated."
}

How to achieve this in laravel sanctum? Thanks in advance.


Solution

  • Rendering exceptions

    Add to ExceptionHandler@register app/Exceptions/ExceptionHandler.php

    $this->renderable(function (\Illuminate\Auth\AuthenticationException $e, $request) {
        if ($request->is('api/*')) {
            return response()->json([
                'message' => 'Not authenticated'
            ], 401);
        }
    });