Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

arma friginiawan's avatar

How to Protect Route by Guard

hello friend,

I have a problem with grouping routes by a guard. I want to create Laravel auth with multiple tables. there is no problem with the login, everything runs well. but when I access a spesific route that has middleware guard, the response is always unauthenticated..

here is my code :

  • routes/api.php
Route::post('register', [AccountController::class, 'register']);
Route::post('login', [AccountController::class, 'login']);
     
Route::middleware('auth:student`)->group( function () {
    Route::resource('products', ProductController::class);
});
  • LoginController.php (login method)
public function login(Request $request)
    {
        if(strtolower($request->grantType) === "user") {
            if(Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])){ 
                $user = Auth::guard('user')->user();
                $success['token'] =  $user->createToken('MyApp')->accessToken;
                $success['name'] =  $user->name;
                $success['guard'] =  Auth::guard('user')->check();
                return $this->sendResponse($success, 'User login successfully.');
            } 
            else{ 
                return $this->sendError('Unauthorized', ['error'=>'Invalid credentials'], 401);
            } 
        } else if (strtolower($request->grantType) === "student") {
            if(Auth::guard('student')->attempt(['email' => $request->email, 'password' => $request->password])){ 
                $user = Auth::guard('student')->user();
                $success['token'] =  $user->createToken('MyApp')->accessToken;
                $success['name'] =  $user->name;
                $success['guard'] =  Auth::guard('student')->check();
                return $this->sendResponse($success, 'Student login successfully.');
            } 
            else{ 
                return $this->sendError('Unauthorized', ['error'=>'Invalid credentials'], 401);
            } 
        } else if (strtolower($request->grantType) === "teacher") {
            if(Auth::guard('teacher')->attempt(['email' => $request->email, 'password' => $request->password])){ 
                $user = Auth::guard('user')->user();
                $success['token'] =  $user->createToken('MyApp')->accessToken;
                $success['name'] =  $user->name;
                $success['guard'] =  Auth::guard('teacher')->check();
                return $this->sendResponse($success, 'Teacher login successfully.');
            } 
            else{ 
                return $this->sendError('Unauthorized', ['error'=>'Invalid credentials'], 401);
            } 
        } else {
            return $this->sendError('Bad Request', ['error'=>'No enum constant '.$request->grantType], 400);
        }
    }
  • config/auth.php
'defaults' => [
        'guard' => 'student',
        'passwords' => 'student',
    ],

'guards' => [
        'user' => [
            'driver' => 'session',
            'provider' => 'user',
        ],
        'teacher' => [
            'driver' => 'session',
            'provider' => 'teacher',
        ],
        'student' => [
            'driver' => 'session',
            'provider' => 'student',
        ],
    ],

'providers' => [
        'user' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        'teacher' => [
            'driver' => 'eloquent',
            'model' => App\Models\Teacher::class,
        ],
        'student' => [
            'driver' => 'eloquent',
            'model' => App\Models\Student::class,
        ], 
    ],
  • ProductController.php (index method)
public function index()
    {
        $products = Product::all();
    
        return $this->sendResponse(ProductResource::collection($products), 'Products retrieved successfully.');
    }

Here is the result when I accessed {{baseUrl}}/api/products :

{
    "message": "Unauthenticated."
}
0 likes
1 reply
Snapey's avatar

api routes are stateless. You need an authentication token.

If your client is a web browser and not a mobile application, put your route in web.php instead so that it can benefit from sessions

Please or to participate in this conversation.