我有路线
http://192.168.10.15/user/33/edit
我正在尝试根据 url id 返回用户。
public function edit($id, \App\User $user)
{
dd($user->id);
return view('user.update');
}
id返回null,我该怎么做?
最佳答案
要使路由绑定(bind)起作用,您应该使类型提示的变量名称与路由段名称匹配,如文档所需的那样:
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');
在你的 Controller 中:
public function edit(\App\User $user)
{
dd($user->id);
return view('user.update')->withUser($user);
}
关于laravel-5 - Laravel Route 模型绑定(bind) - 空用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45481831/