How to Add Custom env Variables in Laravel?

By Hardik Savani | April 9, 2021 | Category : Laravel


This article will give you example of laravel custom env variables. this example will help you laravel environment variables. i explained simply about how to add custom env variables in laravel. i would like to share with you add new custom env variables laravel. Let's get started with laravel create new env variable.

Sometime we may require to add new env variable and use it. i will give you two examples of how to adding new env variable and how to use it with laravel 6, laravel 7 and laravel 8 application.

So, let's follow both example:

Example 1: using env() helper

now first add your new variable on env file as like bellow:

.env

...

GOOGLE_API_TOKEN=xxxxxxxx

Use it:

Route::get('helper', function(){

$googleAPIToken = env('GOOGLE_API_TOKEN');

dd($googleAPIToken);

});

Output:

xxxxxxxx

Example 2: using config() helper

now first add your new variable on env file as like bellow:

.env

...

GOOGLE_API_TOKEN=xxxxxxxx

config/google.php

<?php

return [

'api_token' => env('GOOGLE_API_TOKEN', 'your-some-default-value'),

];

Use it:

Route::get('helper', function(){

$googleAPIToken = config('google.api_token');

dd($googleAPIToken);

});

Output:

xxxxxxxx

now you can check your own.

i hope it can help you...



Tags : Laravel


Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: