如何在 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
How to share Auth::user among all views in Laravel 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.php
file.
我需要将当前登录的用户共享给所有视图。我正在尝试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 user
variable 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())不是。我得到的输出如下:
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());
}
回答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.
看看通配符视图作曲家。