Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Check for the application environment in Laravel views

August 5, 2020 ·

Often you’d come across a scenario where you’d like to check the application environment and based on that you’d like to render things.

For instance, you’d like to check if the environment application currently running in is “production”, you can verify it in the view like so.

@if(App::environment('production'))
    {{-- in "production" environment --}}
@endif

Now, this is alright that we’re leveraging the App::environment method to identify the environment of the application and it even works fine but it’s kind of verbose as you can see.

To fix this, Laravel provided some in-built Blade directives to check for the environment. Here’s how the previous code would translate to if we use Laravel’s in-built Blade directive.

@production
    {{-- in "production" environment --}}
@endproduction

As you can see, it’s pretty straight-forward now. All you need to do is mention the environment name like @environment and end it like @endenvironment so.

If you want to check for multiple environments in a single conditional, you can do it like so.

@env('local', 'staging')
    {{-- in "local" or "staging" environment --}}
@endenv
Learn the fundamentals of PHP 8 (includes 8.1 and 8.2), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?