php 使用 Auth::check() 还是 Auth::user() - Laravel 5.1?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33483532/
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
Which to use Auth::check() or Auth::user() - Laravel 5.1?
提问by tam5
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?
在检查用户是否登录时,是否有理由更喜欢一个?
回答by Thomas Kim
No, the accepted answer is not correct.
不,接受的答案不正确。
Auth::check()
defers to Auth::user()
. It's been that way since as long as I can remember.
Auth::check()
遵从Auth::user()
. 从我记事起就一直这样。
In other words, Auth::check()
calls Auth::user()
, gets the result from it, and then checks to see if the user exists. The main difference is that it checks if the user is null for you so that you get a boolean value.
换句话说,Auth::check()
调用Auth::user()
,从中获取结果,然后检查用户是否存在。主要区别在于它检查用户是否为您为空,以便您获得布尔值。
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()
方法,检查它是否为空,然后返回一个布尔值。
回答by samlev
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()
,它应该简单地检查会话。
回答by Khamroddin
Auth::guard('admin')->user()->email
try this it worked for me.
试试这个它对我有用。
回答by ivahidmontazer
I recomend you to define $user = auth()->user();
If you want to check if user is authenticated or not anduser model properties like email, name, ... in your code.
我建议您在代码中定义$user = auth()->user();
是否要检查用户是否经过身份验证以及用户模型属性,如电子邮件、姓名等。
Because auth()->user()
and auth()->check()
both will query to database. If you want more speed in your apps, define $user = auth()->user();
then you can us it in your codes and also you can check if user is authenticated via $user == null;
.
因为auth()->user()
和auth()->check()
两者都会查询数据库。如果你想提高你的应用程序的速度,定义$user = auth()->user();
然后你可以在你的代码中使用它,你也可以检查用户是否通过$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()
andauth()->user()
来降低对数据库的查询和更快的应用程序!; )