【问题标题】:How to set role name in prefix dynamically for same route group in laravel如何在laravel中为同一路由组动态设置前缀中的角色名称
【发布时间】:2020-12-25 12:52:41
【问题描述】:

我想根据记录的用户角色名称创建动态前缀名称,例如同一路由组 如果管理员在管理面板中登录,那么 网址如:

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');
});

基本上我的路线组对于管理员和经销商来说是相同的 当用户成功登录时我想要根据用户角色使用不同的前缀时

【问题讨论】:

  • Welcome to SO ... 只要有两个组,就不需要以这种方式动态路由
  • 但我只需要更改前缀,管理员和经销商的所有其他事情都相同
  • 用户是如何被引导到这条路线的?

标签: laravel routes roles prefix


【解决方案1】:

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

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

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

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 都将具有此前缀,并且您不必传递它的参数。我们还将从路由中删除前缀参数,这样它就不会传递给您的操作:

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');

注意:这个中间件可以以更广泛的方式应用,但是如果有人没有登录,你需要知道你想为这个参数使用什么默认值。这也是假设你可能有不止 1 个路由那个路由组。如果只有那一条路线,那大概可以稍微调整一下。

【讨论】:

    【解决方案2】:

    这是一个普通的php文件,所以你可以添加

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

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

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

    【讨论】:

    • 如果他们的路由中有这样的条件,他们将无法使用路由缓存,因为缓存路由时满足的条件就是被缓存的路由
    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 2018-11-30
    • 2014-09-29
    • 2021-06-02
    • 2022-11-26
    • 2020-05-17
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多