JackD's avatar

User profile url and route

Hi, I have this format for each user profile "http://domain.com/unique-username" but after testing I notice that user can use route path for their username like (login, index, logout, register). How can I restrict or validate that they must not use those route path as their username?

0 likes
7 replies
ohffs's avatar

You could grab the list of routes and reject the username if it matches? Something heading in the direction of :

$routes = Route::getRoutes();
foreach ($routes as $route) {
    if ($route->getPath() == $username) {
        // reject
    }
}

Or you could do something like laracasts does and prefix the profile route with '@' ?

2 likes
cjke7777's avatar

I feel like this should be tackled at not the route end, but the user validation end. Something like this in your validation rules:

'user_name' => 'not_in:login,logout,register',
1 like
JackD's avatar

@ohffs i used validation "not_in" instead to add some bad words validation but is it a good practice? though it could be a long list :(

martinbean's avatar

@JackD Personally, I don’t like this approach as what happens if someone uses the username ‘about’, and then at a later date you want to add a page at that URI? Also, blacklists can quickly and easily become out of date and out of sync with your routes.

Instead, use a dedicated route, i.e. /profile/{slug}. It’s not pretty, but makes your routing life a lot easier.

3 likes
ohffs's avatar

@JackD doing it manually it's a little fragile imho - you need to remember for the lifetime of your project to keep that list updated (and make it clear to any other dev's who might work with it down the line - maybe after you've passed it on). You could maybe combine the 'not_in' rule with the Route::getRoutes() and build the list into a string though and pass that to not_in. Depends how likely you think the routes are to change I guess.

JackD's avatar

@martinbean i include the routes name inside the list of my "not_in" validation rule, you are right that using /profile/{slug} is not that pretty to look at instead I use a special character for each username as slug in my route

SamSOfficial's avatar

i dont understand the question well.. i think .. you app gives profile page at "http://domain.com/JackD" for example.. so users visit "http://domain.com/logout" gives the same profile page as the other url... if thats the case ... dont just block the keywords out..write a dedicated function for it..

in routes..

Route::get('{username}', array('as' => 'profile', 'uses' => 'YourController@profile'));

on YourController.. write the function as ..

public function profile($username) {

$username = User::where('username', $username)->first();

}

so now.. only a valid username will return your profile page.. the controller code isnt complete.. just an idea about how to do it.. Good Luck..

Please or to participate in this conversation.