Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Check for the application environment in Laravel views

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 (including 8.1, 8.2, and 8.3), 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-digest 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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?