【问题标题】:How to configure a Route resource with root如何使用 root 配置 Route 资源
【发布时间】:2015-09-08 04:12:41
【问题描述】:

我正在使用 Laravel 5.1,并创建了一个路由资源,例如:Route::resource('/page', 'PagesController');。但我不希望/page 成为我的资源,或者/page/about。我宁愿有/about 等。

但是,当我使用 Route::resource('/', 'PagesController'); 时,我的名字和 URI 被毁了。要恢复我使用的名称:

Route::resource('/page', 'PagesController', [
    'names' => [
        'index' => 'pages.index',
        'show' => 'pages.show',
        'create' => 'pages.create',
        'store' => 'pages.store',
        'edit' => 'pages.edit',
        'update' => 'pages.update',
        'destroy' => 'pages.destroy'
    ]
]);

这使/ 将我带到索引文件,但/about 等不起作用,因为URI(显示为{})没有任何参数。

我可以使用$router->get('/', 'PagesController@index"); 等手动设置我的所有路线,但是为所有事情设置其中一个似乎是错误的做法。

如何通过参数设置在根目录下使用的路由资源?

【问题讨论】:

    标签: routes laravel-5


    【解决方案1】:

    我也遇到了同样的问题,但我找不到任何解决方案。

    看一下laravel/framework/src/Illuminate/Routing/ResourceRegistrar.php中的register函数,我们可以看到在这种情况下$base为null:

    // We need to extract the base resource from the resource name. Nested resources
    // are supported in the framework, but we need to know what name to use for a
    // place-holder on the route wildcards, which should be the base resources.
    $base = $this->getResourceWildcard(last(explode('.', $name)));
    
    $defaults = $this->resourceDefaults;
    
    foreach ($this->getResourceMethods($defaults, $options) as $m) {
        $this->{'addResource'.ucfirst($m)}($name, $base, $controller, $options);
    }
    

    这使得添加方法出错:

     * Add the show method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    protected function addResourceShow($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name).'/{'.$base.'}';
    
        $action = $this->getResourceAction($name, $controller, 'show', $options);
    
        return $this->router->get($uri, $action);
    }
    

    我不确定除了手动添加每个方法之外我们是否可以做任何其他事情,但在我的情况下我已经做了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      相关资源
      最近更新 更多