'How to call a controller function inside an if statement in web.php?

I have a route in web.php that looks like this:

Route::get('/dashboard', function () {
    if (Auth::user()->type === 'admin') {
        return view('adminDashboard');
    } elseif (Auth::user()->type === 'manager') {
        // Here I want to call ManagerController@managerDashboard function
    } elseif (Auth::user()->type === 'user') {
        return view('UserDashboard');
    } else return redirect('404');
})->middleware(['auth'])->name('dashboard');

How can I call a controller function in that if statement?



Solution 1:[1]

Given that you are aware that there are better ways of doing this, see https://laravel.com/docs/master/redirects#redirecting-controller-actions

return redirect()->action([ManagerController::class, 'managerDashboard']);

Solution 2:[2]

You can use middleware to make a route group that only can be accessed by specific role, see the docs here

https://laravel.com/docs/9.x/middleware

Solution 3:[3]

write all the if-else statements in the controller.

Route::get('/dashboard', 'DashboardController@index')->middleware(['auth'])->name('dashboard');

In controller create a method name index and write the above code

    public function __construct(){
        $this->middleware('auth');
    }

    public function index(){
    if (Auth::user()->type === 'admin') {
            return view('adminDashboard');
        } 
elseif (Auth::user()->type === 'manager') {
           return view('ManagerDashboard')
        }
 elseif (Auth::user()->type === 'user') {
            return view('UserDashboard');
        } 
else return redirect('404');
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rareclass
Solution 2 Mansjoer
Solution 3 Dip Ghosh