1
votes

im working with laravel 5.5 and tried to protect an api route. I assigned the 'auth' middleware to this route, but when i tested it, i get an InvalidArgumentException aka 'Route [login] is not defined'. Im not reffering to this route in any way, laravel automaticaly tried to redirect to this route. I found the following code line in file 'laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php':

/*
 * Convert an authentication exception into a response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => $exception->getMessage()], 401)
                : redirect()->guest(route('login'));
}

So im wondering, whats the best way to catch this exception globally on every route?

1

1 Answers

0
votes

From my understanding, its because you added an auth middleware to the route. So whenever the route is accessed without an authentication, the route is redirected to the name login route which is the login page by default.

You can add an unauthenticated method to your app/Exceptions/Handler.php with the following code. So if the request is in API or expecting JSON response, it will give a 401 status code with JSON response. If the route is accessed using web routes, it will be redirected to the default page. In the below example, am redirecting it to a login page.

Note: This method existed in the app/Exceptions/Handler.php till laravel 5.4.

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

Don't forget to import use Illuminate\Auth\AuthenticationException;

Edit: Explanation for the error Route [login] is not defined. This is because laravel is trying to redirect to a named route. This named route is available if you are using the laravel auth scaffolding. If you are manually creating the functions, even if the route login exists, it should be named as login. For more information, see https://laravel.com/docs/5.5/routing#named-routes