【问题标题】:Use variable in whole controller在整个控制器中使用变量
【发布时间】:2019-06-10 12:00:25
【问题描述】:

我有一个基于委托角色包的 if 语句,我想使用结果在 laravel 中为我的返回视图添加前缀。我有什么选择?

我现在拥有的:

public function __construct() {        
    if (Auth::user()->hasRole('administrator')) {
        $route = 'admin';
    } else if (Auth::user()->hasRole('company')) {
        $route = 'company';
    } else if (Auth::user()->hasRole('schoolowner')) {
        $route = 'school';
    }
}

public function index()
{
    return view($route.'.person.index', compact('user'))->with('status', 'No school');
}

如何以 laravel 的方式在返回视图函数中使用 if 语句变量?甚至在所有控制器上使用结果

我应该使用中间件吗?或者只是php方式

或者在提供者中查看共享?

【问题讨论】:

  • 尝试在控制器类内部创建protected $route;,然后在底部__construct()内部,写$this->route = $route。那行得通吗?然后,任何其他方法中的$this->route 应该可以工作。让我知道它是否有效
  • 这行得通!节省了很多行,因为我在每个函数中都使用了这个 if 语句。谢谢!
  • 如果你在许多控制器中使用它,你甚至可以把它放在你的基本控制器中:)

标签: php laravel laravel-5 laravel-5.8


【解决方案1】:

创建protected $route; 变量并添加到您的班级 并与$this->route一起使用

protected $route;

public function __construct() {        
    if (Auth::user()->hasRole('administrator')) {
        $this->route = 'admin';
    } else if (Auth::user()->hasRole('company')) {
        $this->route = 'company';
    } else if (Auth::user()->hasRole('schoolowner')) {
        $this->route = 'school';
    }
}

public function index()
{
    return view($this->route.'.person.index', compact('user'))->with('status', 'No school');
}

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多