Let’s say we’re building an app which has two kinds of user - OfficeStaff
and Engineer
. We want them both to hit /dashboard
as their main landing page after login, but they should both see completely different things.
We use the users table for both of them since they both log in the same way, and create a role field to determine who’s the OfficeStaff and who’s the Engineer.
When we create the routes, my first thought was to do this:
Route::group( [ ‘middleware’ => ‘role:office-staff’ ] , function () {
Route::get( ‘dashboard’, function() { return ‘Office staff dash’; } );
} );
Route::group( [ ‘middleware’ => ‘role:engineer’ ] , function () {
Route::get( ‘dashboard’, function() { return ‘Engineer dash’; } );
} );
However the problem is that Laravel doesn’t take middleware into account when compiling routes - it just looks at the path, so the second route overwrites the first one and we don’t have a dashboard route for the office staff.
Since the routes file is loaded before the middleware is run, the Auth middleware doesn’t load in the current user so we can’t dynamically namespace the route like this:
Route::get( ‘dashboard’, [ ‘as’ => ‘dashboard’, ‘uses’ => Auth::user()->role . ‘\DashboardController@dashboard’ ] );
The only other way that occurs to me is detecting it in the controller then creating a new controller instance of the appropriate sub-controller…
public function dashboard( Request $request ) {
App::make( ‘App\Controllers\’ . $request->user()->role . ‘DashboardController’ )->dashboard();
}
But that feels like we’re entering a world of hurt where we lose the ability to type hint inside controller methods, and we’re going to have a LOT of generic controller actions like this.
After all of this, I can't think of a good, clean way to set this up. Any ideas? :)