在我的 routes.php 中我有:
Route::patch('/preferences/{id}', 'UserController@update');
在 View 文件(account/preferences.blade.php)中我有:
{!! Form::model(Auth::user(), ['method' => 'PATCH', 'route' => '/preferences/' . Auth::user()->id]) !!}
但是我收到了这个错误:
Route [/preferences/1] not defined
直接调用route()
helper 也会出现类似的错误:
route('/preferences/' . Auth::user()->id');
我认为我误解了有关此主题的文档,但我已经为带有给定参数的 PATCH 请求定义了一条路由,并在 View 中正确设置了它。我在这里俯瞰什么?
最佳答案
route()
方法,当您在表单打开时执行 ['route' => 'someroute']
时调用,需要所谓的 命名路线。你给路由起这样的名字:
Route::patch('/preferences/{id}',[
'as' => 'user.preferences.update',
'uses' => 'UserController@update'
]);
也就是说,您将路由的第二个参数放入一个数组中,在其中指定路由名称(as
),以及当路由被命中时要执行的操作(使用
)。
然后,当您打开表单时,调用路由:
{!! Form::model(Auth::user(), [
'method' => 'PATCH',
'route' => ['user.preferences.update', Auth::user()->id]
]) !!}
现在,对于没有参数的路由,您可以只执行 'route' => 'routename'
,但是由于您有一个参数,所以您可以创建一个数组并按顺序提供参数。
综上所述,由于您似乎正在更新当前用户的首选项,我建议您让处理 Controller 检查当前登录用户的 ID,并以此为基础进行更新 - 无需发送在 url 和路由中的 id 中,除非您的用户也需要更新其他用户的首选项。 :)
关于php - Laravel 说 "Route not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28714675/