【问题标题】:Laravel URL Generation Not Including ParametersLaravel URL 生成不包括参数
【发布时间】:2015-01-15 22:13:42
【问题描述】:

当我有两条路由指向同一个操作时,我看到 Laravel 4 出现问题,一条在一个组中,一条在 routes.php 文件中“松散”。

<?php     

// Routes.php
Route::group(array('domain' => '{subdomain}.domain.com'), function()
{
        Route::get('profile/{id}/{name}', 'ProfileController@index');
});

Route::get('profile/{id}/{name}', 'ProfileController@index');

// Template.blade.php
<a href="{{ URL::action('ProfileController@index', array(123, 'JimSmith')) }}">Jim Smith</a>

模板链接到:currentsubdomain.domain.com/profile/%7Bid%7D/%7Bname%7D,而不是预期的将 ID 和名称分别交换为 123 和 JimSmith 的行为。

如果我注释掉第一条路线(组内的路线),代码将按预期工作。为什么添加这个额外的路由会破坏 URL 生成?有没有办法解决这个问题?我错过了什么明显的东西吗?

附:对于那些想知道为什么我在两个地方需要这条路线的人,我可以选择使用URL::action('ProfileController@index' array('subdomain' =&gt; 'james', 'id' =&gt; 123, 'name' =&gt; 'JimSmith'); 生成带有子域的url

【问题讨论】:

  • 我不太清楚为什么,但您可以使用命名路由作为替代方案。 Route::get('profile/{id}/{name}', array('as' =&gt; 'yourname', 'uses' =&gt; 'YourController@method')); 然后在您的模板中您可以使用{{ route('yourname') }} 来输出 URL。你可以像往常一样将额外的参数传递给路由:laravel.com/docs/4.2/helpers#urls
  • 如果你注释掉 second 路由而只留下第一个会发生什么?它仍然不起作用吗?换句话说,是 both 导致了问题,还是 第一个 导致了问题?

标签: php laravel laravel-4 laravel-routing


【解决方案1】:

问题是您没有路线的名称/别名,因此它默认为遇到的第一个。

考虑这是一个替代的路线结构:

Route::group(array('domain' => '{subdomain}.domain.com'), function() {
    Route::get('profile/{id}/{name}', [
        'as' => 'tenant.profile.index',
        'uses' => 'ProfileController@index'
    ]);
});

Route::get('profile/{id}/{name}', [
    'as' => 'profile.index',
    'uses' => 'ProfileController@index'
]);

现在您已经命名了这些路线,您可以这样做:

{{ URL::route('profile.index', [123, 'jSmith']) }}

或者:

{{ URL::route('tenant.profile.index', ['subdomain', 123, 'jSmith']) }}

作为一个额外的附加功能,您只能定义一次此路由,然后在所有控制器方法中您将拥有如下内容:

public function index($subdomain = null, $id, $name) { }

然后您可以简单地将www 作为子域传递,并在某处放置一些代码,将 www.domain.com 域从某些操作中打折。

多租户(如果这确实是您所追求的)并不容易且直截了当,但有一些方法可以用来解决某些问题。我实际上正计划写一篇关于它的教程,但现在我希望这会有所帮助。

【讨论】:

  • 感谢您的信息,最后我们不能使用两个不同的名称,因为路径匹配第一个 (subdomain.domain.com) 并将子域传递给控制器​​,所以我选择了您的第二个建议,只定义一次路由并默认子域。
猜你喜欢
  • 2017-11-29
  • 2017-05-18
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 2017-03-19
  • 2013-06-14
  • 2017-04-30
相关资源
最近更新 更多