In this article, I will explain you simple example how to get env variable in Laravel. We can get env variable value in controller and blade file too. We can get env variable using env() helpers function.
What are environment variable in Laravel?
Environment variables are key-value pairs defined in the .env file located at the root of your Laravel project. These variable allow customize the application’s behavior for different environment.
Syntax:
env('VARIABLE_NAME');
Example:
env('APP_URL');
1. How to get env variable in Laravel controller?
You can get environment variable in the controller. You can see below example to get laravel env variable in controller.
Let’see below example How to get env variable in Laravel.
if(env('APP_ENV') == 'local') {
echo "Local Environment";
echo env('APP_ENV');
}
2. How to get env variable in Laravel blade file?
You can get environment variable in the Laravel blade. you can follow below exampele to get env variable in blade file.
Let’see below example how to get env variable in Laravel blade file.
@if(env('APP_ENV') == 'local') {
echo "Local Environment";
echo env('APP_ENV');
}
@endif
Example in a config file:
// config/app.php
'name' => env('APP_NAME', 'Laravel'),
Using a default value is a best practice: env(‘APP_DEBUG’, false) ensures fallback when the variable is missing.
Read also : How to disable model timestamps in Laravel?
I hope this tutorial help you.