Search code examples
phplaravelrouteslaravel-5.3middleware

Laravel reuse URIs with different controllers


I'm playing around with a side-project in Laravel 5.3. I have different user types (such as Administrator, Student etc), and they're properties on the user model:

$user->account_type; // administrator

Each user type has their own dashboard (and other controllers), and their namespaced:

Controllers\Administrator\DashboardController;
Controllers\Student\DashboardController;

All my Controllers and views etc are all namespaced based on the account type.

I want every user (Regardless of type) to be able to do go domain.com/dashboard and be redirected to their account specific controller.

But laravel only recognises the last duplicate uri in the routes file. I read through the Router.php and RouteCollection.php files, and it seems to be because the URI is stored as a key in the array, it'll always be overwritten if you try to reuse it.

I've seen another thread with someone who's tried this, and I don't want to have a single controller with IF's within it (like this):

public function index()
{
    if ($request->user()->account_type == 'administrator') {
        /** **/
    } elseif ... {
    }
}

The reason I don't want single controllers for reused uri's is because I only reuse some URIs. For example the dashboard. I want things consistant, and I don't want to have to do account checks in each controller method I have to reuse.

I've tried to restrict the loading of routes in the middleware, but I can only throw exceptions in the middleware, I can't say "Ignore this group if the middleware fails".

Hopefully I've explained it well enough, but if further info is needed, please comment and let me know.

My question is:

  1. How can I reuse the same URI for different controllers

  2. When in the routing process is the authenticated user retrieved?


Solution

  • 1) Like an option, you can still redirect users in routes file to keep controllers clear:

    \Route::get("dashboard", function(){
        switch(\Auth::user()->account_type){
            case 'admin':
              return (new \App\Http\Controllers\Admin\DashboardController)->index();
            break;
    
            case 'student':
              return (new \App\Http\Controllers\Student\DashboardController)->index();
            break;
        }
    });
    

    2) I suppose user will be already authenticated when accessing dashboard URL, so you can get it with \Auth::user()