Laravel隐式路由模型绑定不起作用。它没有查找标识符指示的记录。我正在获得一个全新的模型对象。
鉴于此代码:
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],
];
});
这个网址:/users/1
我得到这个输出:
[["App\\User",false,[]],["App\\User",true]]
我使用的是PHP 7.2和Laravel 5.6。
附加信息
我在其他Laravel项目中成功完成了隐式路由模型绑定。我正在研究现有的代码库。据我所知,该功能以前没有使用过。
用户记录存在。它没有被软删除。该模型不使用SoftDeletes
特征。
我尝试过使用各种独特的路由名称和其他模型。
我检查了App\Http\Kernel
班的常见罪魁祸首。 $middlewareGroups
在\Illuminate\Routing\Middleware\SubstituteBindings::class,
部分有web
,$routeMiddleware
包含'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
。
它应该在Laravel中没有任何问题。我刚刚在我的Laravel 5.6应用程序中验证了它,这没有问题。
可能的情况你为什么得到这个:
web.php
或api.php
文件中 - 两个组都在bindings
文件中的\Illuminate\Routing\Middleware\SubstituteBindings::class
属性中设置了$midddlewareGroups
(或app/Http/Kernel.php
)
Route::bind('user', function($user) {
return new \App\User();
});
然后你会得到结果,因为你使用自定义逻辑,只返回空用户模型。如果您认为以上都是错误的,我会从新的Laravel 5.6应用程序开始尝试复制该问题。
我终于解决了这个问题。 routes/web.php
的路线没有web
中间件。这通常在app/Providers/RouteServiceProvider.php
函数中的mapWebRoutes()
中完成。在某些时候,在Laravel升级期间,路由定义被破坏了。它看起来像这样:
Route::group([
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
它可以使用旧的定义样式进行更新,如下所示:
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
相反,我只是从latest method chaining style项目中复制了laravel/laravel
,所以它现在看起来像这样:
/**
* 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'));
}