Separating Routes in Laravel 5.3+

Tags

, ,


In a large scale Laravel application the number of routes can grow substantially, and while there are numerous composer packages to simplify the syntax and management of routes, I’ve found that one of the easiest ways to segregate routes and have a nice clean and elegant design is to put my routes into different files and include them into the application as needed.

This method does not require you to re-write your RouteProvider (which may change in structure with new release as it has in the past). Instead, a simple require() call is all that’s needed in your web.php file, as shown below.

#cd routes
#cat web.php
<?php
require(‘admin-routes.php’);
require(‘store-routes.php’);
require(‘test-routes.php’);
Auth::routes();
#
# Catch ALL page router
#
Route::any( ‘{catchall}’, ‘SupportController@user_defined_page’);
#

Where this becomes really handy is for different environments, in the example below I’ve included code to include testing specific routes that I only want to be included in my development environment as defined in my .env file:

<?php
require(‘admin-routes.php’);
require(‘store-routes.php’);
if( env(“APP_ENV”, “NOT_DEFINED”) == “DEV”)
{
    require(‘test-routes.php’);
}
Auth::routes();
#
# Catch ALL page router
#
Route::any( ‘{catchall}’, ‘SupportController@user_defined_page’);

Inside the .env file:

APP_ENV=DEV
APP_DEBUG=true

If you dont set this in the .env file then the config/app.php file has an APP_ENV setting that may need to be set.

-oOo-

 

Advertisements