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

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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