Sometimes, you may need to get .env file variable on blade view and contoller file in laravel 10|9|8 apps. So in this tutorial, you will learn how to get .env file variable in blade view or controller file in laravel 10|9|8 application.
How to Get .env Variable in Blade View & Controller in Laravel 10|9|8
Here are two methods to get .env file variable in blade view or controller in laravel 10|9|8 apps; is as follow:
- Get .env variable in controller
- Using Config and env() Helper Function Get .env variable in blade view
Get .env variable in controller
You can use the following code to get .env file variable in controller; is as follows:
if (env('APP_ENV') == 'local'){ echo 'Local Enviroment'; }
Using Config and env() Helper Function Get .env variable in blade view
You can use the env() helper function to get .env file variable in blade view; is as follows:
@if (env('APP_ENV') == 'local') Local Enviroment @endif
Alternatively, you can set up a configuration variable in the config
directory to access the environment variable more cleanly:
Create a configuration file for your environment variables:
php artisan make:config custom
Open the generated configuration file located in config/custom.php
. Inside this file, define your variables like this:
return [ 'custom_variable' => env('YOUR_CUSTOM_VARIABLE'), ];
In your Blade view, you can now access the environment variable using the config()
function:
<p>My custom variable value: {{ config('custom.custom_variable') }}</p>
Conclusion
In this tutorial, you have learned how to get .env file variable in blade view or controller file in laravel application.