How to get .env variable in blade and controller in LARAVEL?

Spread the love

Hello Guys,

In this article, I will demonstrate a simple example of how to access a “.env variable in blade and controller” in Laravel. This process allows you to access environment variable values within both the controller and blade files. Leveraging the env() helper function available in Laravel versions 6, 7, 8, 9, and 10, we can effortlessly retrieve and utilize values from the .env file.

When I first embarked on my Laravel journey, I encountered a scenario where I needed to retrieve my Google API key from the .env file. Specifically, I had set up a variable named “GOOGLE_MAP_ID” within the .env file, and I needed to access it within JavaScript code embedded in a blade file. To achieve this, I employed the env() function, which provides a convenient means to access and utilize configuration variables.

.Env variable in blade and controller examples:

Also Read: How to Create Custom Helper Functions in LARAVEL 10

Syntax:

env('VARIABLE_NAME');

Example:

Also Read: How to Add Foreign Key in MIGRATION using Laravel?

env('APP_URL');
env('GOOGLE_MAP_ID');

In this article, we present a simple illustration of how to retrieve an environment file variable within a Blade template or controller file.

Blade File:

Also Read: How to Rollback Migration in Laravel?

@if (env('APP_ENV') == 'local')
   Local Enviroment
@endif

@dd(env('GOOGLE_MAP_ID'))

Controller File:

Also Read: How To Send Email In Laravel 9

if (env('APP_ENV') == 'local'){
    echo 'Local Enviroment';
}

echo env('GOOGLE_MAP_ID');

You can conveniently access this valuable information from the environment file.

Uncover the ultimate insights in our collection, your gateway to the best Laravel blog content.

Leave a Comment