[Solved] How to fix this error Symfony\Component\Routing\Exception\RouteNot FoundException: Route [login] not defined. in laravel 8?

Laravel Safiul Tarek


Problem:

Working on notifications in Laravel. Here I am getting an error -

Symfony\Component\Routing\Exception\RouteNotFoundException Route [login] not defined.


Solution 1:

Mostly, this error often occurs when a route protected by middleware is being accessed by an unauthorized/unauthenticated resource. We should check if the jwt token is valid by removing the auth:api middleware and replace it with this:

return response()->json([ 'valid' => auth()->check() ]);


Solution 2:

Use Postman and set the Header `Accept: application/json` otherwise Laravel Passport would never know it's an API client and thus redirect to a /login page for the web.

Route::post('login', [ 'as' => 'login', 'uses' => 'LoginController@do']);

The 'as' portion of the second parameter defines the name of the route. The first string parameter defines its route.


Solution 3:

To check either request includes token or not make your own middleware.

php artisan make:middleware CheckApiToken

public function handle($request, Closure $next)
{
if(!empty(trim($request->input('api_token'))))
{
  $is_exists = User::where('id' , Auth::guard('api')->id())->exists();
      if($is_exists){
               return $next($request);
                    }
}       
  return response()->json('Invalid Token', 401);

Thank you for reading the article. If you face any problems, please comment below.To learn more about laravel 8 you can check

Master Laravel 8 for Beginners & Intermediate course