Detecting the Environment in Blade Files

When you are developing across multiple environments such as locally, UAT and production, one thing you want to be careful of is that you don’t get confused where you are. Uploading test files into production or deleting a customer isn’t the greatest career move you can make.

For me, one of the things I do is to change the colour of something so that it is immediately obvious which environment I am in. An example of this would be when using a Linux shell - I use red text for production, blue for UAT and green for development.

Anyway, I wanted to do something similar today in a project I am working on in Laravel and for this, I thought it would be a good idea to alter the colour of the NavBar based on the environment, but how do you do that in Blade?

As with most Laravel things, it’s not too difficult and here is how. For this, we are going to access the APP_ENV configuration value which states which environment you are in:

1
APP_ENV=local

In Blade, you might choose to access that value this way:

1
2
3
4
5
@if (env('APP_ENV') == 'production')
<nav class="navbar is-warning" role="navigation" aria-label="main navigation">
@else
<nav class="navbar is-primary" role="navigation" aria-label="main navigation">
@endif

I’m using Bulma but that isn’t important; the key is that we are checking the value of the environment variable in our @if statement and changing the nav element based on it.

You could simplify this further by embedding the @if inside the class declaration, but I find that reduces readability - your mileage may vary.

Hope that helps someone.


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com