doujimiao7480 2017-04-30 21:32
浏览 74
已采纳

自动将域参数添加到所有子路由

I'm trying to make it so that I can have all routes inside of a group automatically use a domain parameter without having to specify it in views and whatnot. Here is an example of what I am looking for.

Route group code:

Route::group(['domain' => '{tenant_domain}.myapp.com', 'middleware' => 'tenant'], function () {

The tenant middleware handle:

public function handle($request, $next)
{
    session(['tenant_domain' => $request->route('tenant_domain')]);

    return $next($request);
}

So instead of having to use this code in all my views:

{{ route('login', ['tenant_domain' => session('tenant_domain')]) }}

I'd like to only use:

{{ route('login') }}

And then in the boot() method of RouteServiceProvider, have something like:

public function boot()
{
    if (isset(session('my_parameter'))) {
        Route::addParameter(['tenant_domain' => session('tenant_domain')]);
    }

    parent::boot();
}

How can I do this properly so it works?

  • 写回答

1条回答 默认 最新

  • donkey111111 2017-04-30 21:55
    关注

    Not sure if you automatically bind it to a route. However you can overwrite all Laravel helpers because it is checked if they exist before they are defined:

    if (! function_exists('route')) { //etc }}
    

    So you could rewrite the route function (originally located in Illuminate/Foundation/helpers.php with something like this:

    /**
    * Generate the URL to a named route.
    *
    * @param  string  $name
    * @param  array   $parameters
    * @param  bool    $absolute
    * @return string
    */
    function route($name, $parameters = [], $absolute = true)
    {
        if (session()->has('tenant_domain'))) {
            $parameters = array_prepend($parameters, session()->get('tenant_domain'));
        }
        return app('url')->route($name, $parameters, $absolute);
    } 
    

    You can find how to add a custom helper in this thread.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错