laravel Auth::guest() 为登录和注销的用户返回 true
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34824879/
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
Auth::guest() returns true for both logged in and logged out users
提问by rranj
I am new to laravel and so I was trying to create a small project for learning purpose. I have used the inbuilt Auth for login and register. These automatically generated pages work so well, now In this I created a route to resource posts by using controller called postcontroller.
我是 laravel 的新手,所以我试图创建一个用于学习目的的小项目。我使用内置的 Auth 进行登录和注册。这些自动生成的页面工作得很好,现在我使用名为 postcontroller 的控制器创建了一个资源帖子的路由。
Now in the postcontroller I check if the user is authorized to return a view: posts else to login page. So to check it I do following
现在在 postcontroller 中,我检查用户是否有权返回视图:将其他帖子发布到登录页面。所以为了检查它我做以下
if (!Auth::guest())
return view('posts');
else
return "......";
Now here the Auth::guest() returns true for both logged in and logged out users.
现在这里的 Auth::guest() 为登录和注销的用户返回 true。
回答by Rafael Ferreira
Are you sure that you are logged in?
你确定你登录了吗?
try to dump your Auth::user() data with
尝试转储您的 Auth::user() 数据
dd(Auth::user());
dd(Auth::user());
And by the way, if you are returning in the if statement you do not need to use else.
顺便说一句,如果您在 if 语句中返回,则不需要使用 else。
回答by Clayton.
You need to make sure you use the 'web' middleware. By default, the home page does not use this but the /home route does, which is why the blade templates work under /home.
您需要确保使用“网络”中间件。默认情况下,主页不使用它,但 /home 路由使用,这就是刀片模板在 /home 下工作的原因。
Add the 'web' middleware and dd(Auth::user()) and you'll see better results.
添加 'web' 中间件和 dd(Auth::user()),你会看到更好的结果。
回答by Izac Mac
But You MUST add this line of code for the middleware to know in postcontroller that it needs for check for logged in users.Add this is PostController:
但是您必须为中间件添加这行代码,以便在 postcontroller 中知道它需要检查登录用户。添加这是 PostController:
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
After this you need to make sure the routes are added onto the route list. This is done by adding the given line in Routes/web.php
在此之后,您需要确保将路线添加到路线列表中。这是通过在 Routes/web.php 中添加给定的行来完成的
Route::resource('user','PostController');
recheck if its added by typing the below command in terminal:
通过在终端中键入以下命令重新检查它是否已添加:
php artisan route:list
Once the route is added, the controllers know they can talk to each other, you are all set.
添加路由后,控制器就知道它们可以相互通信了,一切就绪。
Note: Except means user can access ONLY index and show routes if user is logged in . Look at laravel documentationhere for more details. Hope this helps.
注意:除非用户登录,否则表示用户只能访问索引和显示路由。在此处查看 laravel文档以获取更多详细信息。希望这可以帮助。
回答by asghar
you can use
您可以使用
if(!Auth::user())
if(!Auth::user())
//user not login
//用户未登录
else
别的
//user logined
//用户登录