0

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
6
  • Maybe you should define $user Commented Sep 9, 2015 at 10:34
  • @V4n1ll4 you are trying to use variable that is not currently defined enywhere Commented Sep 9, 2015 at 11:08
  • I am trying to define it with {user} Commented Sep 9, 2015 at 11:27
  • 1
    The as directive 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. Commented Sep 9, 2015 at 14:18
  • 1
    as should 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. Commented Sep 9, 2015 at 14:41

1 Answer 1

1

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

http://laravel.com/docs/5.1/routing#route-parameters

Sign up to request clarification or add additional context in comments.

1 Comment

hoe does Laravel define the $user variable in the closure ? I think $user means user_id instead of an object, right ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.