How to Add Custom env Variables and Use It in Laravel

Hello artisan in this example i am going to discuss about laravel set and how to get that env variables from controller. Sometime we may require to add new env custom env variable and need to use it. So i will give you two examples of how to adding new env variable and how to use it in laravel 6, laravel 7 and laravel 8 application.

So if you don't know how we can do that from .env file or laravel config then this tutorial is for you. I want to share with you add new custom env variables laravel. So Let's get started with laravel create new env variable.

 

Example 1

In this example we will do it using env() helper. So let's see the example:

.env

GOOGLE_API_TOKEN=xxxxxxxx

 

And now you can get it like that

Route::get('helper', function(){
    $_token = env('GOOGLE_API_TOKEN');
      
    dd($_token);
  
});

 

Example 2

We can do the same task using config() helper. So set variable on env file as like bellow and Let's see the example:

.env

GOOGLE_API_TOKEN=xxxxxxxx

 

config/google.php

return [
    'api_token' => env('GOOGLE_API_TOKEN', 'your_value'),
];

 

And now call it like below:

Route::get('helper', function(){
    $_token = config('google.api_token');
      
    dd($_token);
  
});

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js