Restricting Laravel routes on the basis of environment

I happened to be going through CodeIgniter’s documentation a few days back, yes CodeIgniter is still around, and I came across something that I considered as quite an interesting feature.

CodeIgniter’s route restriction

CodeIgniter’s routing is setup in such a way that you can create a set of routes that are only available or usable in a specific environment. This can come in handy if for instance in your application you have a set of tools that you would prefer to be only available to the developer on their local machines and be inaccessible on the production environment.

Of course, this set about an interest to see if a similar feature was available on Laravel or if not, if there was an easy work around. After some little research, I came across something on StackOverflow and we are going to look at a modification of the same in this article.

Route restriction in Laravel

Laravel does not ship with an inbuilt mechanism similar to what CodeIgniter has above. However we can whip up something similar using middleware and assigning the middleware to the routes when declaring them.

Scaffold new middleware

php artisan make:middleware RedirectIfProduction

The logic is centered around APP_ENV environment variable, which by default in development is 'local'. Therefore, if the variable is set to any other value other than ‘local’, the request is redirected to the forbidden/403 page.

We have added in a simple extra check, if for instance the env variable is not changed when deployed to production. If the request ip address is not 127.0.0.1, the request is redirected to the aforementioned forbidden page. If the request satisfies both conditions then the request is processed.

Register middleware in Kernel.php file

To be able to utilize the middleware and assign it to specific route, we need to register it in the app/Http/Kernel.php file and assign to it a key or an alias.

Once we have registered the middleware, we can use it in our routes file as so:

Route::get('/profile', function () {
//
})->middleware('dev-env');

Possibilities for modification

This is a overly simplistic implementation and it can be improved in various ways. For instance, the middleware can be modified check for an authenticated user and even an authenticated user of only a specific user role.

Conclusion

You can learn further about Laravel middleware here. Likewise, the implementation on which this article is based on can be found here.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kiptoo Korir

Kiptoo Korir

Web Developer | Information Geek | Occasional Poet - I talk about software development and life in general.