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

Viewed 30457

i have one controller which contains three functions (register,login,forgotPassword).for login and registration it's working fine but when i try to hit an API in postman i am getting an error,previously i use seperate controller for forgotPassword() function at that time it's working fine ,now i moved that controller into USerController i am getting 500 internal server , please help me to fix this issue.. UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Models\PasswordReset;
use App\Notifications\ResetPasswordNotification;


class UserController extends Controller
{
    public function __construct() {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }
    public function register(Request $request)
    {
        $this->validate($request, [
            'fullName'=>'required|string|between:3,15',
            'email'=>'required|email|unique:users',
            'password'=>'required|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/',
            'mobile'=>'required|digits:10'
            ]);
        $user = new User([
            'fullName'=> $request->input('fullName'),
            'email'=> $request->input('email'),
            'password'=> bcrypt($request->input('password')),
            'mobile'=>$request->input('mobile')           
        ]);
        $user->save();
        // User::create($request->getAttributes())->sendEmailVericationNotification();
        return response()->json(['message'=>'Successfully Created user'],201);
    }

    public function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required'
        ]);
        $credentials = $request->only('email', 'password');
        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'Invalid Credentials'], 401);
            }
        }catch (JWTException $e) {
            return response()->json(['error' => 'Could not create token'],500);
        }
        return response()->json(['token' => $token], 200);
    }

    public function forgotPassword(Request $request)
    {
        $user = User::where('email', $request->email)->first();
        if (!$user) {
            return response()->json(['error' => 'Email doesn\'t found on our database'],Response::HTTP_NOT_FOUND);
        }
        $passwordReset = PasswordReset::updateOrCreate(
            ['email' => $user->email],
            [
                'email' => $user->email,
                'token' => JWTAuth::fromUser($user)
            ]
        );
        if ($user && $passwordReset) {
            $user->notify(new ResetPasswordNotification($passwordReset->token));
        }
        return response()->json(['data' => 'Reset link is send successfully, please check your inbox.'], Response::HTTP_OK);
    }
    
}

api.php

<?php

use App\Http\Controllers\UserController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;


Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});


Route::group([
    'middleware' => 'api',
    'prefix' => 'auth'
], function ($router) {
    Route::post('/login', [UserController::class, 'login']);
    Route::post('/register', [UserController::class, 'register']);
    Route::post('verifyemail/{token}','VerificationController@verifyEmail');
    Route::post('/sendPasswordResetLink', 'App\Http\Controllers\UserController@forgotPassword');
    Route::post('/resetPassword', 'App\Http\Controllers\ChangePasswordController@resetPassword');
    //Route::get('/email/verify/{id}',[VerificationController::class,'verify']);

});

in postman i am getting following error

<!doctype html><html class="theme-light">
<!--
Symfony\Component\Routing\Exception\RouteNotFoundException: Route [login] not defined. in file C:\Users\VICKY\Desktop\8\laravel-bookstore\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php on line 427

5 Answers

the route is protected. include Accept application/json in request and it will show: { "message": "Unauthenticated." }

Mostly, I think, this error often occurs when a route protected by a middleware is being accessed by an unauthorized/unauthenticated resource. I think you 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() ]);

Add new config at headers

"Accept"=>"application/json"

Laravel will check the configuration for "Accept", it will return the web page or html if no value is set at "Accept" by default

Source help

PostMan Headers Screenshot for example

In my case the .htaccess file was missing the command to accept the Authorization command.

Command:

CGIPassAuth on

Updated .htaccess with the following command CGIPassAuth on works perfectly fine for me.

<IfModule mod_rewrite.c>
  <IfModule mod_negotiation.c>
    Options -MultiViews
  </IfModule>

  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} -d [OR]
  RewriteCond %{REQUEST_FILENAME} -f
  RewriteRule ^ ^$1 [N]

  RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
  RewriteRule ^(.*)$ public/$1

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ server.php
  
  CGIPassAuth on
</IfModule>

Thanks @Otavio Silva.

Related