Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Shane Meikle
Shane Meikle
13,188 Points

Laravel URL/Route question

Lets say for example a route is set up like:

Route::get('/user/{username}' , 'cController@home');

How would the {username} part of the uri return the actual users name?

1 Answer

When you declare a route like this:

<?php

Route::get('/user/{username}' , 'UsersController@show');

You're saying "anything that looks like "/user/{username}" should be routed to the show method of the users controller. I want the value at position {username} to be passed into the show method as an argument.

If I visited /user/tomcawthorn, laravel will say "Hey! I've got a route that matches that string!" and it will pass the tomcawthorn as $username into the show method.

You show method would look like this:

<?php

/**
 * Show the user
 *
 * @param string $username
 * @return Response
 */
public function show($username)
{
    $username; // tomcawthorn
}

That's what happens - were you asking how it works?

Shane Meikle
Shane Meikle
13,188 Points

Thanks for the answer.

And yeah, I was interested in how it works. Digging deeper into the mechanics behind Laravel has been rather fun, and a learning experience all in its own.