【问题标题】:Laravel Route Model Binding conflict when using the same structure with different modelsLaravel Route Model Binding 在不同模型使用相同结构时发生冲突
【发布时间】:2020-04-15 01:37:51
【问题描述】:

我正在尝试为两个模型创建路由模型绑定:“用户”和“文章”

Route::get('/{user}', 'UsersController@show');

Route::get('/{article}', 'ArticlesController@show');

问题是,其中一个总是优先于另一个,具体取决于它们的声明顺序。

如果用户和文章碰巧有相同的路由,我希望用户路由优先于文章路由,但问题是 laravel 在不匹配用户时返回 404 页面,即使路由应该匹配一篇文章。

我知道您可以为此使用带有正则表达式的 where() 函数,但是这两个模型都对路由键名称使用相同的结构(它们都是字符串)。我可以让正则表达式搜索数据库列或其他内容吗?

【问题讨论】:

  • 选择/users/{user}/articles/{article} 这样的路线是个不错的主意。它不仅可以防止这种情况发生,还可以帮助用户了解他们当前的位置。加上调试。
  • 我同意这是最好的。不幸的是,我的客户希望这样 :)
  • 向他解释与应用该方法相关的技术问题。我完全同意@ThomasVanderVeen 所说的话。但是,如果您想继续这样做。您可以在控制器中解决问题。

标签: php laravel route-model-binding


【解决方案1】:

您有 2 个选项:

  1. 为每条路线使用不同的路线:
Route::get('/users/{user}', 'UsersController@show');

Route::get('/articles/{article}', 'ArticlesController@show');
  1. RouteServiceProvider.php 上自定义解析逻辑:
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    Route::bind('userOrArticle', function ($value) {
        return is_numeric($value)
                    ? App\User::where('id', $value)->firstOrFail()
                    : App\Article::where('title', $value)->firstOrFail();
    });
}
Route::get('/{userOrArticle}', function ($userOrArticle) {
    return $userOrArticle instanceof \App\User
                ? redirect()->action('UsersController@show', ['user' => $userOrArticle]);
                : redirect()->action('ArticlesController@show', ['article' => $userOrArticle]);
});

有关详细信息,请参阅文档的“自定义解析逻辑”部分:https://laravel.com/docs/master/routing#explicit-binding

【讨论】:

  • 他们都在使用字符串
  • 我相信这是我想要的,但是如何根据型号使用不同的控制器呢?如果是用户,则应转到 UsersController@show,文章应转到 ArticlesController@show。
  • @gjerm94 我已根据您的需要更新了答案。
  • 我收到一个错误:“Action App\Http\Controllers\UsersController@show 未定义。”不知道怎么回事
  • @gjerm94 你定义了UsersControllershow 函数了吗?但是,我更喜欢使用单一名称UserController 我根据您的问题信息回答。
猜你喜欢
  • 2014-12-21
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 2011-10-14
相关资源
最近更新 更多