我如何使一个登录的用户对象可用的所有视图在Laravel 5.3


How do I make a logged in user object available to all views in Laravel 5.3

我希望能够在我的视图中获得登录用户的详细信息。例:{{ $user->email }} .

这是我的Controller.php:

public $view_data = array();
public function __construct()
{
    $this->middleware('auth');
    $this->view_data['user'] = Auth::user();
}

$user在我的视图返回NULL。我错过什么了吗?

在默认情况下,它已经在所有视图中可用:

Auth::user()
auth()->user()

您可以通过以下方法直接在视图中访问loggedIn用户:

{!! Auth::user()->name !!}
{!! auth()->user()->name !!}
{!! access()->user()->name !!}

{{'Auth::user()}}{{'Auth::user()['email']}}

Laravel已在您登录后提供此服务。只要写:

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

你也可以为所有视图使用ServiceProvider:

创建服务提供商:php artisan make:provider UserServiceProvider

应用' '供应商UserServiceProvider.php

<?php
namespace App'Providers;
use Illuminate'Support'ServiceProvider;
use Illuminate'Support'Facades'View;
use Auth;
class UserServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    { 
        if(Auth::check()){
            $user= Auth::user();
            View::share('user', $user);
        }
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
    }
}

然后在config'app.php

中注册此服务提供者
App'Providers'UserServiceProvider::class,

现在用户对象可用于所有视图,你只需写:

{{ $user->email }} 
{{ $user->username }}

Laravel与所有视图共享数据