简体   繁体   English

即使用户未登录,如何获取用户(经过身份验证的)信息?

[英]How to get user(authenticated) information even when user is not logged in?

I want to show user information publicly from built-in users table in Laravel. 我想从Laravel的内置用户表中公开显示用户信息。 More specifically, Anyone can see user information( name , email , username ) without logged in. I've used these in blade file: 更具体地说,任何人都无需登录即可查看用户信息( nameemailusername )。我在刀片文件中使用了这些信息:

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

But it only works when user logged in otherwise shows errors. 但是它仅在用户登录时有效,否则显示错误。 Even I've used ELOQUENT in controller and have passed $user object with by view . 甚至我在控制器中使用了ELOQUENT并通过view$ user对象都传递 I'm attaching images so that you can understand my problem. 我附上图片,以便您了解我的问题。 This is my PagesController file 这是我的PagesController文件

<?php

namespace App\Http\Controllers;
use App\Post;
use App\User;

class PagesController extends Controller{
    public function getIndex(){
        $posts=Post::orderBy('id', 'DESC')->paginate(4);
        $user=User::all();
        return view('pages.welcome')->withPosts($posts)->withUser($user);
    }
}

And this is my welcome.blade.php file 这是我的welcome.blade.php文件

<div class="panel-heading">{{ ucwords($user->name) }}</div>

Auth::user takes information of the currently authenticated user. Auth :: user获取当前已认证用户的信息。 So it will o ly work when the user is logged in. 因此,当用户登录时,它将正常工作。

Auth::user() returns the current authenticated user or null for guest users. Auth :: user()返回当前通过身份验证的用户,对于来宾用户为null。 So if you call Auth::user()->name on a guest user it will display the error trying to get property of non-object because its trying to get name from a null object 因此,如果您在访客用户上调用Auth::user()->name ,它将显示trying to get property of non-object的错误trying to get property of non-object因为它尝试从空对象获取名称

You can use something like this in your blade: 您可以在刀片中使用如下所示的内容:

@if(Auth::check())
    User: {{ Auth::user()->name }}
    Email: {{ Auth::user()->email }}
@else
    User: Guest
@endif

If you want to display all users, use the following in your blade: 如果要显示所有用户,请在刀片中使用以下命令:

@foreach(\App\User::all() as $user)
    User: {{ $user->name }}
    Email: {{ $user->email }}
@endforeach

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

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