Laravel 4: Automatically Rerouting Dynamic URL Paths

One of Laravel's many strengths is the power of the Routes file and it's associated functions. Recently, we were developing a site where the authenticated user URLs looked like this:{User ID}/account or{User ID}

This structure works great for allowing "super users" easily navigate through other user pages, without relying on cookies or sessions to keep track of which user's information the page should be displaying as well as making use of Laravels built-in Route Model Binding.

Our logged in user section looked something like this

    'before' => 'auth', 
    'prefix' => 'user/{user}'
  ], function () {

     Route::get('account', '[email protected]');
     Route::get('profile', '[email protected]');

The inconvenience we ran into was we wanted to be able to send the users "generic links" to access their information (eg: This would allow us to include the links in FAQs, as well as make the life of the support team easier by not needing to constantly be generating the dynamic links for each user.

What we did was create a filter and add a route to catch these URLs, and reroute the user to their desired page. Here is how to do it.

First, create a reroute filter in your app/filters.php, file. Remember to update it to match your path name.

| Generic Reroute Filter
| The "generic reroute" filter takes generic logged in user paths and rewrites them to
| include the user's id in the path name, as is expected.
| Must be used in conjunction (and after) the auth filter

Route::filter('reroute', function ()
    return Redirect::to('user/'. Auth::user()->id .'/'. Route::input('path'));


Note, if your URL structure is user/account/{User Id}, simply change the redirect to Redirect::to('user/'. Route::input('path') .'/'. Auth::user()->id);

Then, before your normal "user" route group, add this:

    // Reroute generic links to the correct user paths (from /a to /a/{uid})
    Route::get('a/{path}', ['before' => 'auth|reroute']))->where('path', '[A-Za-z]+');

Now you can send out generic links (eg: /user/account), and utilizing Laravel's built in authentication system, the user will be first redirected to the login form (if not logged in) because of the auth filter.

Then, once authenticated, they will be sent back to their original path user/account, which will be caught and redirected to user/{User Id}/account. Perfect!

Small dog web development studio

View All Our Posts

Web application developers in western Washington, creating user centric web solutions for businesses of all shapes and sizes.

Our projects include ecommerce, event organization, user driven web applications and more.

Small Dog Studios, LLC. Small Dog Studios News