Finishing off the week of advanced routing in Laravel, I am going to mix the techniques while also covering a few more things and giving practical examples.

In the last posts on routing: Multi-TLD Routing and Organizing Routes in Laravel 4, we looked at how to manage subdomain routes and how to include modular route files. Today we will continue looking at Laravel Routes by examining reusable route "partials".

If you are a developer creating subdomain driven applications, it is quite likely that while your production and QA environment may utilize subdomains, your development environment may not. This is where reusable route files come in handy.

For instance if you had an admin section with the traditional routes such as:

Route::group(array('prefix' => 'admin'), function()
{
    Route::get('login', 'Login@create');
    Route::post('login', 'Login@store');
    Route::group(array('before' => 'auth'), function()
    {
        Route::get('/', 'Admin@index');
        // Other Routes
    });
});

But then when you move to production, you have to modify the code to:

Route::group(array('domain' => 'admin.site.tld'), function()
{
    Route::get('login', 'Login@create');
    Route::post('login', 'Login@store');
    Route::group(array('before' => 'auth'), function()
    {
        Route::get('/', 'Admin@index');
        // Other Routes
    });
});

This may not seem like a big deal, but when you are handling mutiple multi-tennant and administration zones, this can become a bit of a nightmare to deal with.

A possible solution would be to include both of the above route groups, but then you run into two problems:

  1. Now *.site.com/admin is a valid route to your administration area
  2. Whenever a route changes in one route group, you will have to update and keep track of two instances of the same code which is not SOLID.

Instead, try using route "partials" similar to the way you would use view partials in your views.

Create a _adminRoutes.php file with the contents:

Route::get('login', 'Login@create');
Route::post('login', 'Login@store');
Route::group(array('before' => 'auth'), function()
{
    Route::get('/', 'Admin@index');
    // Other Routes
});

And in your routes.php file use the following:

if ($tld = get_tld()) { // Method from the Mutli-TLD post
    Route::group(array('domain' => 'admin.site'.$tld), function()
    {
        require __DIR__ . '/_adminRoutes.php';
    });
} else {
    Route::group(array('prefix' => 'admin'), function()
    {
        require __DIR__ . '/_adminRoutes.php';
    });
}

Now when you modify any admin routes, you will be effecting the change across all of your various environments. This also has the benifit of reducing the amount of possible routes that have to be parsed and evaluated upon runtime since only one environment's routes will exist at a time.