Search

Getting the Environment Name in Laravel 4

October 29, 2013 —John Koster

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:

1 
2Route::get('/', function()
3{
4 if (App::environment() == 'local')
5 {
6 // Do something here only if the application is running
7 // in the local environment.
8 }
9});

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:

1<?php
2 
3 Route::get('/', function()
4 {
5 if (App::environment('local'))
6 {
7 // Do something here only if the application is running
8 // in the local environment.
9 }
10 });

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.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.