In Laravel 4, I found that if I want to attach a before
filter to all routes of a website, I can use the App::before()
method which exists in app/filters.php
file, like this:
App::before(function($request)
{
// my code here..
});
But because I discovered that I can't use Route::currentRouteName()
method inside the App::before()
method, I looked for another way to do this, and I found that I can create a custom filter in app/filters.php
file, like this:
Route::filter('my_filter_name', function()
{
// my code to apply on all routes..
});
And in app/routes.php
file, I wrote the next pattern based filter:
Route::when('*', 'my_filter_name');
And it did exactly what I want, and I can use Route::currentRouteName()
method as I want within my custom filter. But I noticed (and correct me if I'm wrong) that Route::when()
method consider my_filter_name
as a before
filter. Now I want to know: How to use this Route::when()
method to apply before
and/or after
filters?
You can do this
In your Routes
Route::group(array('before/after' => 'my_filter_name'), function()
{
Route::get('/', function()
{
// Has my_filter_name Filter
});
Route::get('another', function()
{
// Has my_filter_name Filter
});
});
Unfortunately Laravel gives you no possibility to add a pattern after filter with Route::when()
. The proper way to do this is by wrapping your routes in a group:
Route::group(array('after' => 'my_filter_name'), function(){
// routes
});
If you really really can't use a group, there is another solution. It's a bit hacky though...
After all routes are registered (normally at the bottom of routes.php
) you can add this code that loops over all routes and adds the after filter to each route:
foreach(Route::getRoutes() as $route){
$route->after('my_filter_name');
}