Laravel 不同模型使用相同结构时路由模型绑定冲突

Laravel Route Model Binding conflict when using the same structure with different models

我正在尝试为两个模型创建路由模型绑定:"User" 和 "Article"

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

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

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

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

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

您有 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]);
});

有关详细信息,请参阅文档的 'Customizing The Resolution Logic' 部分:https://laravel.com/docs/master/routing#explicit-binding