php 如何在laravel 5.4中获取当前用户ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45522428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get current user id in laravel 5.4
提问by Mansour hassan
I used this code in Laravel 5.4 to get the current logged in user id
我在 Laravel 5.4 中使用此代码来获取当前登录的用户 ID
$id = User::find(Auth::id());
dd($id);
but I receive "Null"
但我收到“空”
回答by Amitesh
You may access the authenticated user via the Auth facade:
您可以通过 Auth 门面访问经过身份验证的用户:
use Illuminate\Support\Facades\Auth;
// Get the currently authenticated user...
$user = Auth::user();
// Get the currently authenticated user's ID...
$id = Auth::id();
You may access the authenticated user via an Illuminate\Http\Request
您可以通过 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.
}
via the Auth helper function:
通过 Auth 帮助函数:
auth()->user(); //returns an instance of the authenticated user...
auth()->user()->id ; // returns authenticated user id.
回答by Laerte
You have to call user()
method:
你必须调用user()
方法:
$id = \Auth::user()->id;
Or, if you want to get only the model:
或者,如果您只想获取模型:
$user = \Auth::user();
回答by Bashirpour
Using Helper:
使用助手:
auth()->user()->id ; // or get name - email - ...
Using Facade:
使用外观:
\Auth::user()->id ; // or get name - email - ...
Using DI Container:
使用 DI 容器:
use Illuminate\Auth\AuthManager;
class MyClass
{
private $authManager;
public __construct(AuthManager $authManager)
{
$this->authManager = $authManager;
}
}