Scroll to top

Advanced Routing and Filters in Laravel

I think you are interested in more than Basic Routing, let’s go deeper into routing concept in Laravel framework. In this tutorial we will check Route filters, Named Routes and Route Groups in detail.

Let’s take a look at how you can achieve an URL in laravel even though your route is something else. Suppose you want to achieve an SEO URL as http:://domain.com/profile but your route is something like this user/profile. But you don’t need to worry you can achieve whatever URL you want using named routes concept in routing like below.

Route::get('user/profile', array('as' => 'profile', function()
{
    return 'User Profile';
}));

In named routes, you can also specify controller methods instead of Closures like below.

Route::get('user/profile', array('as' => 'profile', 'uses' =>'userController@showProfile'));

Now you use the route like below when redirecting or generating a link.

$url = URL::route('profile');
 
$redirect = Redirect::route('profile');

Now suppose our blog needs an admin section to do CRUD operations on blog posts. But it needs to be separated from users section and also it needs to be protected from crazy people for that we will add Authentication and also admin URL’s should start with /admin.

Route Prefixing allows us to add /admin to the beginning of the every admin URL. So we don’t have to add Route::get(‘admin/something’).. to every route.

Route Groups helps us to apply prefixing on all the routes of admin section like below.

// app/routes.php
 
Route::group(array('prefix' => 'admin'), function()
{
      // home page route to the admin section
      Route::get('/', function()
      {
        return 'Admin Home Page';
      });
 
      // Route to the all posts listing 
      Route::get('posts', function()
      {
           return 'Dashboard page';
      });
 
      // Route to create a new blog post
      Route::get('posts/create', function()
      {
           return 'New post created';
      });
});

Now our next step is to protect all the /admin routes from other users. This we can achieve using Routes Filters. Route filters provide a way to limit access to the routes, which is useful for creating authentication for all the routes which are accessible after authentication.

// app/routes.php
 
Route::group(array('prefix' => 'admin','before' => 'auth'), function()
    {
                // home page route to the admin section
        Route::get('/', function()
        {
            return 'Admin Home Page';
        });
 
        // Route to the all posts listing 
        Route::get('posts', function()
        {
            return 'Dashboard page';
        });
 
        // Route to create a new blog post
        Route::get('posts/create', function()
        {
            return 'New post created';
        });
    });

In Laravel framework, there are so many inbuilt filters like auth, auth.basic, guest and csrf filters. All these filters are located in app/filters.php file. You can define your own Route Filter like Laravel Auth filter. Let’s define our own Route Filter.

Route::filter('old', function() 
{
  if(Input::get('age') < 200)
  {
    return Redirect::to('home');
  }
});

Let’s use the defined filter in one of the Route.

Route::get('user', array('before' => 'old', function() {
 
   return 'You are 200 years old!';
 
}));

In the same way, let’s attach a filter to a Controller action.

Route::get('user', array('before'  =>  'old', 'uses'  =>  'userController@showProfile' ));

We can use multiple Filters in a single Route like below.

Route::get('user', array('before' => 'auth|old', function() {
 
   return 'You are authenticated and 200 years old!';
 
}));

For advanced filtering, it’s better to use a class instead of Closure. We can register a class-based filter like below.

Route::filter('foo', 'FooFilter');

By default, the filter method on the FooFilter class will be called.

Class FooFilter{
 
   public function filter()
  
   {
 
       // code logic will go here
 
    }
 
}

To know more about Laravel Global and Default filters check app/filters.php file.

App::before(function($request)
{
     //
});
 
App::after(function($request,$response)
{
 //
});
 
Route::filter('auth', function()
{
    if (Auth::guest())
    {
        if (Request::ajax())
        {
            return Response::make('Unauthorized', 401);
        }
        else
        {
            return Redirect::guest('login');
        }
    }
});
 
 
Route::filter('auth.basic', function()
{
    return Auth::basic();
});
 
Route::filter('guest', function()
{
    if (Auth::check()) return Redirect::to('/');
});
 
Route::filter('csrf', function()
{
    if (Session::token() !== Input::get('_token'))
    {
        throw new Illuminate\Session\TokenMismatchException;
    }
});

We can also run certain Routes like payment transaction on https instead of HTTPFor this kind of situations, we can use Secure Routes like below.

Route::get('secret/content', array('https', function() {
    
    return 'Secure page';
    
});

If we want to show different content for the same route based on domain name, we can use Domain Routing like below.

Route::group(array('domain' => 'domain.com', function() {
    
    Route::get('blog/aboutus', function() {
      return 'Main blog about us page';
    });
});
 
Route::group(array('domain' => 'dev.domain.com', function() {
    
    Route::get('blog/aboutus', function() {
      return 'Dev blog about us page';
    });
});
 
Route::group(array('domain' => 'test.domain.com', function() {
    
    Route::get('blog/aboutus', function() {
      return 'Test blog about us page';
    });
});

These are the advanced Routing concepts in laravel. In this tutorial, I didn’t go through fully about Filters. I will explain in detail about Filters in future tutorials.

Thanks

KodeInfo


Author avatar

admin

http://www.kodeinfo.com
Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Post a Comment

Your email address will not be published. Required fields are marked *