【问题标题】:Laravel 5.2 assigning same route to different controller action by conditionsLaravel 5.2按条件将相同的路由分配给不同的控制器动作
【发布时间】:2016-10-18 17:05:28
【问题描述】:

我希望根据用户类型将相同的路由路由到不同的控制器。

    if (Auth::check() && Auth::user()->is_admin) {
        Route::get('/profile', 'AdminController@show');
    } elseif (Auth::check() && Auth::user()->is_superadmin) {
        Route::get('/profile', 'SuperAdminController@show');
    }

但这不起作用。

我怎样才能让它按我想要的方式工作?

【问题讨论】:

  • 您的超级管理员控制器与管理员控制器之间是否存在重大差异?我个人会路由到同一个控制器并使用 Auth 逻辑来确定控制器上要执行的方法。在路由文件中包含逻辑通常不是最佳实践
  • 谢谢 Rob,我知道这样做不是一个好习惯。 Admin 和 SuperAdmin 在我的系统中将有一个非常不同的仪表板和功能。这就是为什么我希望将它们分成 2 个控制器和动作。
  • 这是你的答案link

标签: php laravel laravel-5 controller routes


【解决方案1】:

你可以这样做

    Route::get('/profile', 'HomeController@profile'); // 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

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

【讨论】:

  • 谢谢你们,终于它与 HomeController 作为中间人一起工作了。看来这是目前唯一的解决方案。再次非常感谢。
  • 别管它的编辑工作了,很高兴它对你有用
【解决方案2】:

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

你的路线组会是这样的

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

        if (Auth::check() && Auth::user()->is_admin)
        {
            Route::get('profile', 'AdminController@show');
        }
        else
        {
            Route::get('profile', 'SuperAdminController@show');
        }

    });

希望对你有帮助。

【讨论】:

  • 我认为最好将逻辑排除在路由文件之外:3
  • 我回答了他的问题,我回答了他确切需要知道的内容
  • 当然可以,但永远不要忘记最佳实践:3
  • 感谢 H.Fakher,但在我的情况下它不起作用,不知道为什么。但我让它与上面的另一个解决方案一起工作。再次感谢。
猜你喜欢
  • 2013-09-24
  • 2016-03-29
  • 2017-04-05
  • 2016-10-03
  • 2018-12-12
  • 1970-01-01
  • 2016-06-04
  • 2016-05-16
  • 2016-03-03
相关资源
最近更新 更多