Laravel 5路线未定义,而它是?

2022-01-08 00:00:00 routes php laravel laravel-5

我对这应该如何工作感到有些困惑.但我收到 Route [/preferences/1] not defined 错误.

I'm a little confused on how this is supposed to work. But I'm getting an Route [/preferences/1] not defined error.

在我的 routes.php 中我有:

In my routes.php I have:

Route::patch('/preferences/{id}', 'UserController@update');

在视图文件(account/preferences.blade.php)中我有:

And in the view file (account/preferences.blade.php) I have:

<代码>{!!Form::model(Auth::user(), ['method' => 'PATCH', 'route' => '/preferences/' . Auth::user()->id]) !!}

我收到一条错误消息,告诉我路线不存在.我想我误解了关于这个主题的文档,但我认为我已经为带有给定参数的 PATCH 请求定义了一个路由,并在视图中正确设置了它.

I'm getting an error telling me the route doesn't exist. I think I'm misunderstanding the docs on this topic but in my opinion I've defined a route for PATCH requests with a given parameter, and set this in the view correctly.

我在这里俯瞰什么?

推荐答案

route() 方法,当你做 ['route' =>'someroute'] 在表单打开时,需要所谓的命名路由.你给一个路线起这样的名字:

The route() method, which is called when you do ['route' => 'someroute'] in a form opening, wants what's called a named route. You give a route a name like this:

Route::patch('/preferences/{id}',[
    'as' => 'user.preferences.update',
    'uses' => 'UserController@update'
]);

也就是说,您将路由的第二个参数放入一个数组中,您可以在其中指定路由名称(as),以及当路由被命中时要执行的操作(<代码>使用).

That is, you make the second argument of the route into an array, where you specify both the route name (the as), and also what to do when the route is hit (the uses).

然后,当你打开表单时,你调用路由:

Then, when you open the form, you call the route:

{!! Form::model(Auth::user(), [
    'method' => 'PATCH',
    'route' => ['user.preferences.update', Auth::user()->id]
]) !!}

现在,对于没有参数的路由,你可以这样做 'route' =>'routename',但是由于你有一个参数,你可以创建一个数组并按顺序提供参数.

Now, for a route without parameters, you could just do 'route' => 'routename', but since you have a parameter, you make an array instead and supply the parameters in order.

综上所述,由于您似乎正在更新当前用户的首选项,我建议您让处理控制器检查当前登录用户的 id,并以此为基础进行更新 - 无需发送在 url 和路由中的 id 中,除非您的用户也需要更新其他用户的首选项.:)

All that said, since you appear to be updating the current user's preferences, I would advise you to let the handling controller check the id of the currently logged-in user, and base the updating on that - there's no need to send in the id in the url and the route unless your users should need to update the preferences of other users as well. :)

相关文章