隐式路由模型绑定 [英] Implicit Route Model Binding
问题描述
Laravel的隐式路由模型绑定不起作用.它不查找标识符指示的记录.我正在得到一个全新的模型对象.
Laravel's implicit route model binding isn't working. It is not looking up the record indicated by the identifier. I'm getting a brand new model object.
给出以下代码:
Route::get('users/{user}', function (App\User $user, $id) {
$user2 = $user->find($id);
return [
[get_class($user), $user->exists, $user],
[get_class($user2), $user2->exists],
];
});
此URL:/users/1
我得到以下输出:
[["App\\User",false,[]],["App\\User",true]]
我使用的是PHP 7.2和Laravel 5.6.
I'm on PHP 7.2 and Laravel 5.6.
其他信息
我已经在其他Laravel项目中成功完成了隐式路由模型绑定.我正在开发现有的代码库.据我所知,该功能以前没有使用过.
I've successfully accomplished implicit route model binding in other Laravel projects. I'm working on an existing codebase. As far as I can tell, the feature hasn't been used previously.
用户记录存在.尚未被软删除.该模型不使用SoftDeletes
特征.
The user record exists. It has not been soft deleted. The model does not use the SoftDeletes
trait.
我已经尝试过使用各种唯一的路由名称和其他模型进行此操作.
I've tried this using various unique route names and other models.
我已经检查了App\Http\Kernel
类中常见的罪魁祸首. $middlewareGroups
在web
部分中具有\Illuminate\Routing\Middleware\SubstituteBindings::class,
,而$routeMiddleware
包含'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
.
I've checked the App\Http\Kernel
class for the usual culprits. $middlewareGroups
has \Illuminate\Routing\Middleware\SubstituteBindings::class,
in the web
section and $routeMiddleware
contains 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
.
推荐答案
我终于解决了这个问题. routes/web.php
中的路由没有web
中间件.这通常是在mapWebRoutes()
函数中的app/Providers/RouteServiceProvider.php
中完成的.在某个时候,在Laravel升级期间,路线定义被弄乱了.看起来像这样:
I finally resolved this issue. The routes in routes/web.php
did not have the web
middleware. This is normally done in app/Providers/RouteServiceProvider.php
in the mapWebRoutes()
function. At some point, during a Laravel upgrade, the route definition got mangled. It looked like this:
Route::group([
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
可以使用较旧的定义样式对其进行更新,使其看起来像这样:
It could have been updated, using that older definition style, to look like this:
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
相反,我只是复制了最新方法链接 laravel/laravel
项目中的样式,因此现在看起来像这样:
Instead, I just copied the latest method chaining style from the laravel/laravel
project, so it now looks like this:
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
这篇关于隐式路由模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!