ItSolutionStuff.com

How to Add Custom env Variables in Laravel?

By Hardik Savani • April 16, 2024
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, laravel 8, laravel 9, laravel 10 and laravel 11 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

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Blade Foreach Loop Example

Read Now →

Laravel Blade Check If Variable is Set or Not Example

Read Now →

How to Define Constant Variable in Laravel?

Read Now →

Define Global Variable in Laravel 5.8

Read Now →

Laravel - How to Get .env Variable in Blade or Controller?

Read Now →

Laravel Deployment on Cloudways with Envoyer

Read Now →

How to Get Current Controller or Method Name in Codeigniter?

Read Now →

Laravel $loop Variable New Feature Example

Read Now →

How to Get Current Controller Name in View Laravel?

Read Now →

How to Pass Data to All Views using Composer Share in Laravel?

Read Now →

How to Define Global Variables in Laravel?

Read Now →