Only run code in production – Laravel

At times you will need to add code for production that you don’t want to trigger while working in your dev environment. Laravel makes this super easy by allowing us to utilize the config set in the .env file.

Look for the following in your .env file

APP_ENV=local

On your production server this should be set to

APP_ENV=production

We can easily check the config from inside a blade template and execute on the result. In this case: does the .env file say we are in production or local environment.

@if(config('app.env') == 'production') 

<!-- check the config, 
if we are in production environment then run the analytics code -->

<!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxxxxxxxx-x"></script>
<script>    
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-xxxxxxxxx-x');
</script>
@endif

This simple setting can come in handy for little things like this. This isn’t limited to just analytics code, you can use it for almost anything. However I would keep it’s use to only where necessary.