Laravel 5 route not defined, while it is?

Ben Fransen picture Ben Fransen · Feb 25, 2015 · Viewed 178.1k times · Source

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

In my routes.php I have:

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

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

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

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.

What am I overlooking here?

Answer

Joel Hinz picture Joel Hinz · Feb 25, 2015

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'
]);

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]
]) !!}

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.

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. :)