Fabrizio Fenoglio
Fabrizio Fenoglio

Reputation: 5947

Laravel 4 Route with username on first segment

i want to undestrtand how can i setup my routes on the best way for not get collission on the future.

I would like have like first segment the username of the user showing the profile of that user.

Example: laravel.dev/user1

the problem is, if i have a route with the name register "example below" and a user put like username register of course happen a collission and is not sure on wich view is showed.

Route::get('register','UserController@getCreate');

I setup my main route for display the profile user like so:

    Route::get('{cr_user}','WallController@getIndex');    // view profile

    Route::bind('cr_user', function($value, $route) {
    if($user = User::where('username', '=',$value)->first()) // check if exist the user other ways show 404 page
    {
        return $user;
    }
    App::abort(404);
});

The second problem of this setting of route is that i cannot set other route with just 1 segment. Example if i want set the route register i cannot do that without put any segment before but for do it work i have to put example: do/register.

any help?

Upvotes: 0

Views: 404

Answers (1)

na-98
na-98

Reputation: 889

Here is how I think you can achieve the desired result. Although it's not full proof but I think it will work (I haven't tested it yet). Also like Anam said you want to put this route at the bottom of the page.

Basically you can get the list of routes currently in Laravel App by the following:

<?php
$routes = Route::getRoutes();
foreach ($routes as $r) {
    $route_names = array();
    $firstSegment = explode('/', $r->getPath());
    //echo $firstSegment[0] ."<br>";
    array_push($route_names, $firstSegment[0]);
    var_dump($route_names);
}
 ?>

You now have an array or routes first segment of the URL. Use these as a reserved word when users sign up to your App and throw an error if there is a match. This will prevent the collision. But this won't prevent you from creating a new route with a username that already exists so search your Database before adding a new route :)

I'm pretty sure there there may be a good solution to this but this is what comes to my mind. I don't like to add /profile/ that just isn't elegant.

Upvotes: 1

Related Questions