在整个控制器中使用变量

Use variable in whole controller

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

我现在拥有的:

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 的方式在 return 视图函数中使用 if 语句变量?甚至在所有控制器上使用结果

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

或在提供者中查看份额?

创建 protected $route; 变量并添加到您的 class 并将其与 $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');
}