Laravel 路由模型绑定 - 空用户

Laravel Route model binding - empty user

我有路线

http://192.168.10.15/user/33/edit

我正在尝试 return 基于 url id 的用户。

  public function edit($id, \App\User $user)
    {
        dd($user->id);
         return view('user.update');

    }

ID 为 returning null,我该怎么做?

要使路由绑定正常工作,您应该让类型提示变量名称与路由段名称相匹配,正如文档所要求的那样:

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:

Route::get('api/users/{user}', function (App\User $user) {
return $user->email; });

Since the $user variable is type-hinted as the App\User Eloquent model and the variable name matches the {user} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.

针对您的情况:

Route::get('/users/{user}/edit', 'YourController@edit');

在你的控制器中:

public function edit(\App\User $user)
{
     dd($user->id);
     return view('user.update')->withUser($user);

}

如果您最近升级到 laravel 5.3 及更高版本,您可能需要检查是否已更新 laravel/app/Http/Kernel.php 以注册用于绑定替换的路由中间件。

Route model binding is now accomplished using middleware. All applications should add the Illuminate\Routing\Middleware\SubstituteBindings to your web middleware group in your app/Http/Kernel.php file:

\Illuminate\Routing\Middleware\SubstituteBindings::class,

You should also register a route middleware for binding substitution in the $routeMiddleware property of your HTTP kernel:

'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,

Once this route middleware has been registered, you should add it to the api middleware group:

'api' => [
    'throttle:60,1',
    'bindings',
],

我通过添加命名路由修复了它。如果没有为路由指定名称,模型绑定将不起作用。

Route::get('product/{product}', "ProductController@read")->name('product.read');