Laravel 5, View::Share

2019-02-09 22:52发布

I'm trying to do a view::share('current_user', Auth::User()); but in laravel 5 i can't find where to do this, in L4 you could do this in the baseController, but that one doesn't exists anymore.

grt Glenn

5条回答
疯言疯语
2楼-- · 2019-02-09 23:20

I am using Laravel 5.0.28, view::share('current_user', Auth::User()) doesn't work anymore because this issue https://github.com/laravel/framework/issues/6130

What I do instead is, first create a new service provider using artisan.

php artisan make:provider ComposerServiceProvider

Then add ComposerServiceProvider to config/app.php providers array

//...
'providers' => [
    //...
    'App\Providers\ComposerServiceProvider',
]
//...

Then open app/Providers/ComposerServiceProvider.php that just created, inside boot method add the following

/**
 * Bootstrap the application services.
 *
 * @return void
 */
public function boot()
{
    View::composer('*', function($view)
    {
        $view->with('current_user', Auth::user());
    });
}

Finally, import View and Auth facade

use Auth, View;

For more information, see http://laravel.com/docs/5.0/views#view-composers

查看更多
爷的心禁止访问
3楼-- · 2019-02-09 23:25

This will may help:

App::booted(function()
{
    View::share('current_user', Auth::user());
});
查看更多
We Are One
4楼-- · 2019-02-09 23:28

In Laravel 5 uses the same method as in laravel 4:

View::share('current_user', Auth::User());

or using the view helper:

view()->share('current_user', Auth::User());

See in http://laravel.com/docs/5.0/views

查看更多
甜甜的少女心
5楼-- · 2019-02-09 23:32

I'v tried it, put it in app/Providers simply not working. The alternative way is to create a Global middleware and put View::share('currentUser', Auth::user()); there.

查看更多
smile是对你的礼貌
6楼-- · 2019-02-09 23:34

First, you can probably create your own BaseController and extend it in other controllers.

Second thing is, that you may use Auth:user() directly in View, you don't need to assign anything in the view.

For other usages you can go to app/Providers/App/ServiceProvider.php and in boot method you can View::share('current_user', Auth::User()); but or course you need to add importing namespaces first:

use View;
use Auth;

because this file is in App\Providers namespace

查看更多
登录 后发表回答