[英]Which to use Auth::check() or Auth::user() - Laravel 5.1?
If I want to check whether the user is logged in within my Laravel 5.1 application I can either use 如果我想检查用户是否在我的Laravel 5.1应用程序中登录,我可以使用
if (Auth::user()) {...}
or 要么
if (Auth::check()) {...}
is there a reason to prefer one over the other when checking if a user is logged in? 在检查用户是否已登录时,是否有理由优先选择其中一个?
No, the accepted answer is not correct. 不,接受的答案是不正确的。
Auth::check()
defers to Auth::user()
. Auth::check()
遵循Auth::user()
。 It's been that way since as long as I can remember. 只要我记得,就一直这样。
In other words, Auth::check()
calls Auth::user()
, gets the result from it, and then checks to see if the user exists. 换句话说, Auth::check()
调用Auth::user()
,从中获取结果,然后检查用户是否存在。 The main difference is that it checks if the user is null for you so that you get a boolean value. 主要区别在于它检查用户是否为空,以便获得布尔值。
This is the check function: 这是检查功能:
public function check()
{
return ! is_null($this->user());
}
As you can see, it calls the user()
method, checks if it's null, and then returns a boolean value. 如您所见,它调用user()
方法,检查它是否为null,然后返回一个布尔值。
If you just want to check if the user is logged in, Auth::check()
is more correct. 如果您只想检查用户是否已登录,则Auth::check()
更正确。
Auth::user()
will make a database call (and be slightly heavier) than Auth::check()
, which should simply check the session. Auth::user()
将进行数据库调用(并且稍微重一点Auth::check()
,而不是Auth::check()
,它应该只检查会话。
Auth::guard('admin')->user()->email
试试这个对我有用。
I recomend you to define $user = auth()->user();
我建议你定义$user = auth()->user();
If you want to check if user is authenticated or not and user model properties like email, name, ... in your code. 如果要检查用户是否已通过身份验证, 并且在代码中检查用户模型属性(如电子邮件,名称,...)。
Because auth()->user()
and auth()->check()
both will query to database. 因为auth()->user()
和auth()->check()
都会查询到数据库。 If you want more speed in your apps, define $user = auth()->user();
如果您想在应用中获得更高的速度,请定义$user = auth()->user();
then you can us it in your codes and also you can check if user is authenticated via $user == null;
然后你可以在你的代码中使用它,你也可以检查用户是否通过$user == null;
身份验证$user == null;
. 。
Don't use auth()->check()
and auth()->user()
both in one function or one block of code to have low queries to database and more speed apps! 不要在一个函数或一个代码块中使用auth()->check()
和auth()->user()
来对数据库和更快速的应用程序进行低查询! ; ; ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.