如何在Laravel中为同一路由组动态设置前缀中的角色名称

问题描述

我想根据登录用户角色名称来创建动态前缀名称,例如相同的路由组 如果管理员管理面板登录,则 网址类似:

http://localhost:8000/admin/dashboard

并且,如果经销商正在管理面板登录

http://localhost:8000/dealer/dashboard

我的路线组是

Route::group(['prefix' => 'admin','as' => 'admin.','namespace' => 'Admin','middleware' => ['auth','verified','preventBackHistory']],function () {
    Route::get('/dashboard','HomeController@index')->name('home');
});

基本上,我的路线组与管理员和经销商相同 当我成功登录后,根据用户角色需要不同的前缀

解决方法

注意:这是对您正在做的事情的一些假设。

在注册路由之后,您将无法访问有关当前用户的信息。在将请求分派到路由并通过中间件堆栈后,会话才开始。这是关于如何以对事件顺序有意义的方式实现此目标的想法。

您应该使用动态前缀设置路由组:

Route::group(['prefix' => '{roleBased}','as' => 'admin.','namespace' => 'Admin','middleware' => ['auth','verified','dealWithPrefix','preventBackHistory']],function () {
    Route::get('/dashboard','HomeController@index')->name('home');
});

然后在RouteServiceProvider中,将为前缀参数roleBased添加一个约束,以仅允许其为adminclient

public function boot()
{
    // restrict the prefix to only be 'admin' or 'dealer'
    \Route::pattern('roleBased','admin|dealer');

    parent::boot();
}

现在,您将必须创建一个中间件来处理获取当前用户的信息,以为此前缀设置默认值,以便您为这些路由生成的所有URL都具有该前缀,而您不必传递参数。我们还将从路由中删除prefix参数,以免将其传递给您的操作:

public function handle($request,$next)
{
    $role = $request->user()->role; // hopefully 'admin' | 'client'

    // setting the default for this parameter for the current user's role
    \URL::defaults([
        'roleBased' => $role
    ]);

    // to stop the router from passing this parameter to the actions
    $request->route()->forgetParameter('roleBased');
    
    return $next($request);
}

将此中间件在您的内核中注册为dealWithPrefix。请注意,该中间件上方的路由组中已将其添加到中间件列表中。

如果您需要生成指向该组中任何路由的URL,而当前请求不是该组中的路由之一,则在生成URL时将需要为此前缀传递一个参数:

route('admin.home',['roleBased' => ...]);

如果当前正在请求该组中的一条路由,则无需添加此参数:

route('admin.home');

注意:可以以更广泛的方式应用此中间件,但是如果有人未登录,则需要知道要为该参数使用的默认值。这还假设您在其中可能只有多个路由。该路线组。如果只有一条路线,则可能会稍作调整。

,

这是一个普通的php文件,因此您可以添加

if(...){ // if admin
    $prefix = 'admin';
}else{ // if dealer
    $prefix = 'dealer';
}

在您的路线之前和您的路线中:

Route::group(['prefix' => $prefix,'as' => $prefix.'.','namespace' => ucwords($prefix),'HomeController@index')->name('home');
});