How to check if user logged in or no Laravel

  Kiến thức lập trình

this code in Laravel where I want to use it as API to show it for every one that visit my app. and I want to get user ID when he is logged in

public function show($displayType)
{
    try {
        $data = houses::where('displayType', $displayType)->paginate(5);

        $user = auth()->user(); // Get the authenticated user

        $userId = $user ? $user->id : null; // Check if user is authenticated and get the user ID

        return response()->json([
            'status' => true,
            'message' => 'You have successfully retrieved data',
            'data' => $data,
            'user_id' => $userId, // Include the user ID in the response
        ]);
    } catch (Throwable $th) {
        return response()->json([
            'status' => false,
            'message' => $th->getMessage(),
        ], 500);
    }
}

I want to check if the person that visited my site is logged in or no

But the problem is when I send token is return user id null
that’s how use my route request.
// this my route I use it out the middleware check

Route::get('houses/{displayType}',[housesController::class, 'show']);

Route::middleware('auth:api')->group(function () {})

LEAVE A COMMENT