Reputation:
I am a newbie when it comes to Laravel and so far really enjoying it. I'm using L4 and would like some help with the routing which I'm still trying to get my head around.
I would like the uri domain.com/{username}
I can get domain.com/{user_id}
and Laravel looks up the user but I cannot seem to use the username as a parameter.
EDIT:
I am using a model for user routing
Route::model('user', 'User');
And then trying to route
Route::get('/{user}', 'sampleController@viewUser');
Also note that it's after all other routes
Thanks in advance!
Upvotes: 1
Views: 1089
Reputation: 9007
Even better, you can use Route::bind()
:
Route::bind('user', function($value, $route)
{
return User::whereUsername($value)->first();
});
Now, you can access that user without manually calling it in the route definition:
Route::get('{user}', function(User $user){
if (!is_null($user)) {
return View::make('profile', compact('user'));
}
});
This will be available to all routes you define that use the {user}
parameter.
Upvotes: 0
Reputation: 22862
Hi there and welcome to Laravel!
You can use this route registration.
Route::get('{username}', function($username){
$user = User::whereUsername($username)->fist();
if (! is_null($user)) {
return View::make('profile', compact('user'));
}
});
... but if you go to mysite.com/blog
or mysite.com/contact
or whatever, this URL would be captured by previous pattern.
Actually no problem, just register blog/contact/whatever route before, like this!
Route::get('blog', function(){
return 'blog page';
});
Route::get('contact', function(){
return 'contact page';
});
// To have username in URL discard Route::model call and add this
Route::get('{username}', function($username){
$user = User::whereUsername($username)->fist();
if (! is_null($user)) {
return View::make('profile', compact('user'));
}
});
Upvotes: 3
Reputation: 752
You could try this without the Route::model thingy
Route::get('user/{username}', function($username)
{
$user = User::where('username',$username)->first();
})
->where('name', '[A-Za-z]+');
Upvotes: 0