2016-06-17 30 views
0

我希望根据用户类型将相同的路由路由到不同的控制器。Laravel 5.2根据条件将不同的控制器动作分配到相同的路由

if (Auth::check() && Auth::user()->is_admin) { 
     Route::get('/profile', '[email protected]'); 
    } elseif (Auth::check() && Auth::user()->is_superadmin) { 
     Route::get('/profile', '[email protected]'); 
    } 

但是,这是行不通的。

我该如何让它按照我想要的方式工作?

+0

你的超级管理员控制器和管理员控制器之间有一个主要区别吗?我个人会路由到同一个控制器,并使用Auth逻辑来确定控制器上要执行的方法。在您的路线文件中使用逻辑通常不是最佳做法 –

+0

感谢Rob,我知道这样做不是一个好习惯。 Admin和SuperAdmin在我的系统中将有一个非常不同的仪表板和功能。这就是为什么我希望将它们分成两个控制器和操作。 –

+0

这里去你的答案[链接](http://stackoverflow.com/questions/31368433/single-laravel-route-for-multiple-controllers) –

回答

3

你可以做到这一点

Route::get('/profile', '[email protected]'); // another route 

控制器

public function profile() { 
     if (Auth::check() && Auth::user()->is_admin) { 
      $test = app('App\Http\Controllers\AdminController')->getshow(); 

      } 
     elseif (Auth::check() && Auth::user()->is_superadmin) { 
     $test = app('App\Http\Controllers\SuperAdminController')->getshow(); 
     // this must not return a view but it will return just the needed data , you can pass parameters like this `->getshow($param1,$param2)` 

     } 

     return View('profile')->with('data', $test); 
      } 

但我认为它能够更好地使用特质

trait Show { 

    public function showadmin() { 
    ..... 
    } 
    public function showuser() { 
    ..... 
    } 
} 

然后

class HomeController extends Controller { 
    use Show; 
} 

然后你就可以做同样作为上述但不是

$test = app('App\Http\Controllers\AdminController')->getshow();// or the other one 

使用本

$this->showadmin(); 
$this->showuser(); // and use If statment ofc 
+0

感谢这两个,最后它与HomeController作为中间人。看来这是目前唯一的解决方案。再次感谢。 –

+0

没关系编辑它的剂量工作,很高兴它为你工作 –

1

好,你可以做到这一点通过创建route::group

路线组会like that

route::group(['prefix'=>'yourPrefix','middleware'=>'yourMiddleware'],function(){ 

     if (Auth::check() && Auth::user()->is_admin) 
     { 
      Route::get('profile', '[email protected]'); 
     } 
     else 
     { 
      Route::get('profile', '[email protected]'); 
     } 

    }); 

我希望能帮到你。

+0

我认为它更好地保持路线文件的逻辑:3 –

+0

我回答了他的问题,我回答了他确切需要知道的内容 –

+0

是当然,但永远不会忘记最佳实践:3 –

相关问题