How to make laravel passport auth redirect in json response?

Viewed 2468

I am trying to create API with laravel passport authentication now it is very easy to make API with laravel passport. I am using personal access token to create access token for API users. As my client and server are both one, but when token not provided in the API it redirect to login page create by laravel auth scaffold php artisan make:auth, I want to return json response with message "Token not provided."

https://laravel.com/docs/5.4/passport#personal-access-tokens

I am using auth:api in routes.

How to pass json response for API if token not provided?

2 Answers

I also encountered this same issue. To solve that redirection, you have to pass header of the request of json response. for that i made decision to make middleware as below

public function handle($request, Closure $next)
{
    $request->headers->set('Accept', 'application/json');
    return $next($request);
}

the above middleware will force the header to add json response, group the api collection as below

Route::group(['middleware' => 'json.response'], function () {

 //your routes here

});
Related