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条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用