沃梦达 / 编程问答 / php问题 / 正文

多个控制器的单个 Laravel 路由

Single Laravel Route for multiple controllers(多个控制器的单个 Laravel 路由)

本文介绍了多个控制器的单个 Laravel 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个项目,其中我有多种用户类型,例如.superadmin、admin、managers 等.一旦用户通过身份验证,系统会检查用户类型并将其发送到相应的控制器.用于此的中间件工作正常.

I am creating a project where i have multiple user types, eg. superadmin, admin, managers etc. Once the user is authenticated, the system checks the user type and sends him to the respective controller. The middle ware for this is working fine.

所以当经理去 http://example.com/dashboard 时,他会看到经理仪表板,而当管理员去到他可以看到管理仪表板的同一个链接.

So when manager goes to http://example.com/dashboard he will see the managers dashboard while when admin goes to the same link he can see the admin dashboard.

下面的路线组单独工作正常,但放在一起时只有最后一个工作.

The below route groups work fine individually but when placed together only the last one works.

/*****  Routes.php  ****/
 // SuperAdmin Routes
    Route::group(['middleware' => 'AppHttpMiddlewareSuperAdminMiddleware'], function () {
        Route::get('dashboard', 'SuperAdmindashboard@index'); // SuperAdmin Dashboard
        Route::get('users', 'SuperAdminmanageUsers@index'); // SuperAdmin Users
    });

 // Admin Routes
    Route::group(['middleware' => 'AppHttpMiddlewareAdminMiddleware'], function () {
        Route::get('dashboard', 'Admindashboard@index'); // Admin Dashboard
        Route::get('users', 'AdminmanageUsers@index'); // Admin Users
    });

我知道我们可以重命名路由,如超级管理员/仪表板和管理员/仪表板,但我想知道是否还有其他方法可以实现干净的路由.有没有人知道任何解决方法?

顺便说一句,我使用的是 LARAVEL 5.1

感谢任何帮助:)

推荐答案

我能想到的最佳解决方案是创建一个控制器来管理用户的所有页面.

The best solution I can think is to create one controller that manages all the pages for the users.

routes.php 文件中的示例:

example in routes.php file:

Route::get('dashboard', 'PagesController@dashboard');
Route::get('users', 'PagesController@manageUsers');

您的 PagesController.php 文件:

your PagesController.php file:

protected $user;

public function __construct()
{
    $this->user = Auth::user();
}

public function dashboard(){
    //you have to define 'isSuperAdmin' and 'isAdmin' functions inside your user model or somewhere else
    if($this->user->isSuperAdmin()){
        $controller = app()->make('SuperAdminController');
        return $controller->callAction('dashboard');    
    }
    if($this->user->isAdmin()){
        $controller = app()->make('AdminController');
        return $controller->callAction('dashboard');    
    }
}
public function manageUsers(){
    if($this->user->isSuperAdmin()){
        $controller = app()->make('SuperAdminController');
        return $controller->callAction('manageUsers');  
    }
    if($this->user->isAdmin()){
        $controller = app()->make('AdminController');
        return $controller->callAction('manageUsers');  
    }
}

这篇关于多个控制器的单个 Laravel 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:多个控制器的单个 Laravel 路由

基础教程推荐