When creating a web app, we may find a few routes that need the same URL prefix or filter.
Using Laravel’s route groups, we can easily apply these to multiple routes.
For this recipe, we just need a standard installation of Laravel.
How to do it…
To complete this recipe, follow these steps:
1. In our app/filters.php file, create a filter to check for a user:
if (‘user’ !== Session::get(‘profile’))
return ‘You are not Logged In. Go Away!’;
2. In the app/routes.php file, create a route that can set our profile session:
3. In routes.php, create our route group:
Route::group(array(‘before’ => ‘checkUser’, ‘prefix’ =>
return ‘I am logged in! This is my user
return ‘This would be a list of my friends’;
4. In our browser, we then go to http://path/to/our/server/profile/user,
where we will get an error. If we then go to http://path/to/our/server/setprofile,
it will redirect us and show the correct page.
How its Works..
The first thing we need to do is create a filter. This simple filter will check a session name,
profile, to see if it equals user. If not, it won’t let us proceed any further.
Back in our routes, we then create a route that will set the profile session for us and then
redirect us to the route group. Setting the session would normally be done after logging in, but
here we’re just testing to make sure it works.
Finally, we create our route group. For this group, we want every route within it to run through
the checkUser filter before allowing access. We also want these routes to have profile/
come before them. We do this by adding them to the array just before we call the group’s
closure. Now, any route we create inside this group must pass the filter and will be accessible
using the profile prefix.