How to get env(environment variable) in Laravel blade file and controller :
In this article, you will learn how can we get the env variable in the blade file or controller
Table of content : –
what is env variable
Laravel get variable in blade file with env(‘’); function
Laravel get variable in controller with env(‘’); function
get variable in controller with value
What is an env variable?
.env file contains variables that can be set according to the application’s environment for example(APP_NAME). In the env file, variables are defined or assigned random values, depending on the application’s environment. it kind of works as a key and values.
Syntext :
env(‘VARIABLE_NAME’);
laravel get variable in blade file with env(‘’); function:
environment-variable.blade.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Get Environment Variable</title> </head> <body> <h2 style="text-align:center;margin-top:10%;"> Environment Variable is : <?php echo env('APP_NAME'); ?> </h2> </body> </html>
OUTPUT :
Laravel get variable in the Controller with env(‘’); function
public function environmentVariable() { $envVariable = env('APP_NAME'); return view('environment-variable', compact('envVariable')); }
If the variable is not defined in the else file, then the variable in the else function can also be defined with a value. For example :
public function environmentVariable() { $envVariable = env('APP_NAME', 'Laravel'); return view('environment-variable', compact('envVariable')); }
Define variable in config.php file :
<?php use Illuminate\Support\Facades\Facade; return [ /* |-------------------------------------------------------------------------- | Application Name |-------------------------------------------------------------------------- | | This value is the name of your application. This value is used when the | framework needs to place the application's name in a notification or | any other location as required by the application or its packages. | */ 'name' => env('APP_NAME', 'Laravel'), /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services the application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_NAME', 'Laravel'), // some other variables goes here ];
Variables in .env File –
Sensitive keys are also defined in environment variables, so we do not post the .env file variables publicly like in Git Hub.