douyu4535 2016-09-18 14:07
浏览 34
已采纳

Laravel 5.3 - 将$ user变量共享给所有视图

So after finding out that sharing views in Controller.php's constructer no longer works because it always returns null to Auth::user(), I am looking for a different way to do it.

I am simply looking for a way to pass a $user variable with the current signed in user to all my views.

Previous way which worked in 5.2 and below:

public function __construct()
{
    view()->share('signed_in', Auth::check());
    view()->share('user', Auth::user());
 }

This no longer works. How else can I share variables?

I have tried:

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->user = Auth::user();
        $this->signed_in = Auth::guest();

        view()->share('signed_in', $this->signed_in);
        view()->share('user', $this->user);

        return $next($request);
    });
}

But the code above does not work. It does load the page without a "Undefined Variable $user" error but it just show the navigation bar and then nothing else. It also messes up the site CSS for some reason.

Is there any other way I can do it? Please help. Thank you.

  • 写回答

3条回答 默认 最新

  • douhuocuo9012 2016-09-19 17:01
    关注

    I fixed this issue quite easily.

    In my \App\Http\Controllers\Controller.php

    class Controller extends BaseController
    {
        use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    
        private $user;
        private $signed_in;
    
        public function __construct()
        {
            $this->middleware(function ($request, $next) {
                $this->user = Auth::user();
                $this->signed_in = Auth::check();
    
                view()->share('signed_in', $this->signed_in);
                view()->share('user', $this->user);
    
                return $next($request);
            });
    
        }
    
    }
    

    By putting the view()->share() in a closure of a middleware, I was able to achieve this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?