0
votes

Using laravel5.8. Using both web and API(Token Gaurd).
when using api call with invalid api_token parameter receiving an error Route:Login not defined. I want the response in JSON. Read in Forum I need to use the below way in app\Exceptions\Handler.php and it works. I have web gaurd for some of the paths. I want the route:login to work when its a web gaurd and return json response when using api gaurd. How can I do it in Laravel 5.8?

  public function render($request, Exception $exception)
    {
      //  dd(get_class($exception));
       // return parent::render($request, $exception);
        return response()->json(
            [
                'errors' => [
                    'status' => 401,
                    'message' => 'Unauthenticated',
                ]
            ], 401
        );
    }
1

1 Answers

1
votes

I put the logic in unauthenticated function, combines with expectsJson() should solve your problem

// in app\Exceptions\Handler.php
public function render($request, Exception $exception)
{
    return parent::render($request, $exception);
}

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['status' => 401,'message' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest('/');
}