Laravel自动在每个视图中获取并绑定值

时间:2019-06-21 15:52:32

标签: laravel cookies view extract bind

我有一个后端/管理员Laravel应用程序,该应用程序使用cookie值将边栏的状态设置为打开,折叠或浮动。

我要尝试的是根据登录用户的令牌在cookie中添加值。我尝试在控制器的$this->userToken = Auth::user()->token;中编写代码__construct(),但是它不起作用。我收到此错误Trying to get property of non-object

但是,如果我用控制器的任何方法编写代码,它都可以正常工作而不会出错。我用谷歌搜索了这个问题,发现了几种解决方案,但是没有一个能够解决它。

我也尝试过View作曲家。

控制器:

/**
 * Private variables
 */
private $controller  = "";
private $action      = "";
private $arrayCookie = "";

public function __construct(Route $route)
{
    /** 
     * Middlewares
     */
    $this->middleware('auth');
    $this->middleware('cookies');
    $this->middleware(function ($request, $next) {
        $userToken         = Auth::user()->token;
        $this->arrayCookie = $request->$userToken;

        return $next($request);
    });

    /** 
     * Extracting current controller & action from the namespace
     */
    list($controller, $method) = @explode("@", $route->getActionName());

    /** 
     * Assigning values to private variables
     */
    $this->controller = preg_replace('/.*\\\/', '', $controller);
    $this->action     = preg_replace('/.*\\\/', '', $method);
}

public function <method>()
{
    ...
    # rendering view
    return view(self::DIRECTORY . "create", [
        ...

        **'arrayCookie' => $this->arrayCookie,**

        ...
    ]);
    ...
}

...

查看:

...

<div id="main"<?php
    # fetching cookie -> sidebar-floating
    if(!empty($arrayCookie['sidebar-floating']) && $arrayCookie['sidebar-floating'] == true)
    {
        echo ' class="sidebar-floating"';
    }
?>>

...

0 个答案:

没有答案