如何在 laravel 5.4 中获取当前用户 ID

2022-08-30 12:22:56

我在Laravel 5.4中使用此代码来获取当前登录的用户ID

    $id = User::find(Auth::id());
    dd($id);

但我收到“空”


答案 1

您可以通过身份验证外观访问经过身份验证的用户:

use Illuminate\Support\Facades\Auth;

// Get the currently authenticated user...

$user = Auth::user();

// Get the currently authenticated user's ID...

$id = Auth::id();

您可以通过 Illuminate\Http\Request 访问经过身份验证的用户

use Illuminate\Http\Request;
public function update(Request $request)
{
     $request->user(); //returns an instance of the authenticated user...
     $request->user()->id; // returns authenticated user id. 
}

通过身份验证帮助程序函数:

auth()->user();  //returns an instance of the authenticated user...
auth()->user()->id ; // returns authenticated user id. 

答案 2

您必须调用方法:user()

$id = \Auth::user()->id;

或者,如果您只想获取模型:

$user = \Auth::user();

推荐