Home > OS >  Laravel Passport How to show custom error message when invalid token is supplied
Laravel Passport How to show custom error message when invalid token is supplied

Time:10-17

Actually am trying to create api with Laravel passport, and I have to protect some routes so that only authenticate user can access this routes.

Route::post('register', [ApiAuthController::class, 'register']);
Route::post('login', [ApiAuthController::class, 'login']);
Route::middleware('auth:api')->group(function () {
    Route::post('/task', [ApiControllerTaskController::class,'store']);
});

Now here after login I got access token and I used this access token like this. enter image description here

everything is working fine here but when I remove bearer token then I want to show kind of invalid token error message but I got this. enter image description here

CodePudding user response:

Make sure you added the Content-type : application/json in your headers in Postman before sending your request

CodePudding user response:

This worked for me, If your laravel version is >= 8.* add this code to your Handler.php witch located in App/Exceptions/Handler.php

public function render($request, Throwable $e)
{
    if ($e instanceof AuthenticationException) {
        return response()->json($e->getMessage());
    }
    return parent::render($request, $e);
}

If you need more help, leave me a commment. I hope I can help:)

  • Related