简体   繁体   English

在Laravel中返回经过身份验证的用户的最佳实践

[英]Best practice for returning authenticated users in laravel

I had a bit confusion in authentication, i'm a Laravel user since version 5.2. 我在身份验证方面有些困惑,从5.2版开始,我就是Laravel用户。 But in this scenario on version 5.6, I create a middleware that checks the authenticated users, the logout function was perfect but, i try to access the page with my middleware, it returns 但是在这种情况下,在5.6版上,我创建了一个中间件来检查经过身份验证的用户,注销功能是完美的,但是,我尝试使用中间件访问该页面,它返回

Trying to get property 'name' of non-object

Because i had a function that fetches the name of Authenticated User. 因为我有一个获取身份验证用户名称的函数。

How can i handle this scenario? 我该如何处理这种情况?

My Middleware code: 我的中间件代码:

   public function handle($request, Closure $next) {
    if (Auth::check()) {
     return $next($request);
    }
    return redirect()->route('login');
}

In the page: 在页面中:

{{Auth::user()->name}}

Thanks 谢谢

You get this error because the current user is not authenticated. 您收到此错误,因为当前用户未通过身份验证。 You can use the optional() helper: 您可以使用optional()帮助器:

{{ optional(auth()->user())->name }}

Or: 要么:

{{ auth()->check() ? auth()->user()->name : 'Please login' }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM