stack stack - 1 month ago 14
PHP Question

How can I create dynamic routes?

I have this path:

http://localhost:8000/home


I want when a regular user opens path above, then I call this controller:

mainPage@index


But when a admin opens that path, then I call this controller:

panelPage@index


So as you see, I'm looking for "dynamic routes" kinda .. Is implementing that possible? In other word, can I call two different controllers for admin and regular member ?

Answer

For best practice, you could use Middleware to sort-out and categorize your routes and controllers.

In this - relatively simple - case, you could also use something like this (in your routes file):

if(!is_null(Auth::user()))  {
  // first check if user is logged in, else Auth::user() will return null
  $uses = 'mainPage@index';
  if(Auth::user()->admin) {
    $uses = 'panelPage@index';
  }
  Route::get('/', $uses);
}

Update

Or you could wrap everything inside this if statement in an auth middleware group, like this:

Route::group(['middleware' => ['auth']], function(){
   $uses = 'mainPage@index';
    if(Auth::user()->admin) {
     $uses = 'panelPage@index';
    }
    Route::get('/', $uses);
});

Also make sure that your users table has a column named 'admin'.