如何在 Laravel 5 中的所有视图之间共享 Auth::user?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30135792/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:31:04  来源:igfitidea点击:

How to share Auth::user among all views in Laravel 5?

phplaravellaravel-5

提问by Chris

I need to share the currently logged in user to all views. I am attempting to use the view->share()method within AppServiceProvider.phpfile.

我需要将当前登录的用户共享给所有视图。我正在尝试view->share()AppServiceProvider.php文件中使用该方法。

I have the following:

我有以下几点:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Contracts\Auth\Guard;


class AppServiceProvider extends ServiceProvider {


    public function boot(Guard $guard)
    {
        view()->share('guard', $guard);
        view()->share('user', $guard->user());
    }

    //..
}

However, when I hit up a view (after logging in), the uservariable is null. Strangely, the $guard->user(the protected attribute, not the public method user()) is not. The output I get is the following:

但是,当我打开一个视图(登录后)时,该user变量为空。奇怪的是,$guard->user(受保护的属性,而不是公共方法 user())不是。我得到的输出如下:

enter image description here

在此处输入图片说明

Note the guard->user variable is populated, but the user variable is null.

请注意,guard->user 变量已填充,但 user 变量为空。

回答by TomLingham

Better off using View Composers for this one.

最好为此使用 View Composers。

In your ComposerServiceProvider in boot():

在您的 ComposerServiceProvider 中boot()

view()->composer('*', 'App\Http\ViewComposers\GlobalComposer');

In HTTP/ViewComposers create a class GlobalComposer, and create the function:

在 HTTP/ViewComposers 中创建一个类 GlobalComposer,并创建函数:

public function compose( View $view )
{
    $view->with('authUser', Auth::user());
}

http://laravel.com/docs/5.0/views#view-composers

http://laravel.com/docs/5.0/views#view-composers

回答by hayatbiralem

You can solve this problem without creating a file.

您可以在不创建文件的情况下解决此问题。

Add these codes to boot() action of your ServiceProvider and that's it.

将这些代码添加到您的 ServiceProvider 的 boot() 操作中,就是这样。

view()->composer('*', function($view){
  $view->with('user', Auth::user());
});

Source also same: http://laravel.com/docs/5.0/views#view-composers

来源也相同:http: //laravel.com/docs/5.0/views#view-composers

Look Wildcard View Composers.

看看通配符视图作曲家