如何检查用户是否登录Laravel

问题描述 投票:0回答:1

Laravel 中的这段代码,我想将其用作 API 来向每个访问我的应用程序的人显示它。我想在他登录时获取用户ID

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);
    }
}

我想检查访问我网站的人是否已登录

但问题是当我发送令牌时返回用户 ID null 这就是如何使用我的路线请求。 // 这是我的路线,我在中间件检查中使用它

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

Route::middleware('auth:api')->group(function () {})
laravel
1个回答
0
投票

使用

check()
功能验证用户是否已登录。

if (auth()->check()) {
    // User is logged in
    $user = auth()->user();
} else {
    // User is not logged in
}

在 Blade 中,还可以使用指令来简化这些函数的调用。

@auth
    // The data only available for auth user
@endauth

// and

@guest
    // Show content if unauthenticated
@endguest
© www.soinside.com 2019 - 2024. All rights reserved.