Laravel 10|9|8 Get .env Variable in Blade View & Controller

Laravel 10|9|8 Get .env Variable in Blade View & Controller

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.

Recommended Laravel Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *