Getting the Environment Name in Laravel 4

2 min read

Environments in Laravel 4 are a great way to develop your application and have it respond to the environment it is running in. For example, most applications have two environments that they will ever run in: local and production. You can think of the local environment as your development machine and the production environment is the server where your end users access the application.

Using environments, our Laravel 4 application can automatically change to a different database server or use a different cache driver. However, when we are writing our own code and would like to check the environment name for some reason, we can do it like this:


 Route::get('/', function()
 {
     if (App::environment() == 'local')
     {
         // Do something here only if the application is running
         // in the local environment.
     }
 });

The above code example accesses the application object by using the App facade. It then calls the environment() method which returns the name of the current environment name as a string. We could actually simplify the above code by passing the name of the environment we want to check for into the environment() method:

<?php

 Route::get('/', function()
 {
     if (App::environment('local'))
     {
         // Do something here only if the application is running
         // in the local environment.
     }
 });

When we pass the name of the environment into the environmnet() function, Laravel 4 returns a boolean value indicating whether or not our application is running in the environment specified. Both code examples function the same, and which method you use will most likely come down to personal style.

Comments

There are no comments. Be the first to comment!

Up next