How can I do the following in Laravel 5.1:
Route::get('/users/{user}', ['as' => $user, 'uses' => 'UserController@index']);
The code above gives an error:
Undefined variable: user
Routing fails because you defined a $user variable as the route name, so Laravel returns an error.
Route names are useful for reverse routing, as an example when you define redirect or action attribute in your form.
Check the documentation to know how to pass variable by routes.
EDIT: Here the link to the doc for Laravel 5.1 ( which is similar to previous version btw ). A good practice is passibg the variable or an array of variables using a closure.
Route::get( '/users/{user}', function( $user ) {
return $user;});
And this one using correct route naming:
Route::get('/users/{user}', ['as' => 'userroute', function( $user ) {
return $user;}]);
$user variable in the closure ? I think $user means user_id instead of an object, right ?
$user{user}asdirective in the route parameters describes a name for the route. It has nothing to do with the parameters in the route. So what you're trying to do there doesn't make sense. Check out the docs and then come back & describe what you're trying to do.asshould be a string, i.e.'as' => 'user.show'. It is the name of the route, it is not what the value of the{user}parameter should be. For that, check out route–model binding.