DutchPrince
DutchPrince

Reputation: 363

Use variable in whole controller

I have an if statement based on entrust roles package, and i want to use the outcome to prefix my return views in laravel. What options do i have?

What i have now:

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');
}

How can i use the if statement variable inside return view function in a laravel way? Or even use the outcome on all controllers

Should i use middleware? Or just the php way

Or view share in provider?

Upvotes: 1

Views: 69

Answers (1)

Ali Ghaini
Ali Ghaini

Reputation: 905

create protected $route; variable and add to your class and use it with $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');
}

Upvotes: 3

Related Questions