How to Get env Variable in Laravel 9 Blade Templates

Share this Article
Reading Time: 3 minutes
303 Views

Inside this article we will see the concept i.e How To Get env Variable in Laravel 9 blade templates. Article contains the classified information about accessing environment variables values within laravel template blade templates.

Blade templates in laravel are the standard view files formats. They have their own syntax to work with. We will see some methods by which we can get env variable values in blade templates.

env variables values are defined inside .env file which you can find at application root. You will see it contains the default environment values. You can create custom env variables too.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Set Environment Variable

To define environment values, you use .env file inside application root.

APP_NAME="Online Web Tutor"
APP_ENV=local
APP_KEY=base64:xyz...
APP_DEBUG=true
APP_URL=http://localhost

...

Here, you can see we have taken few env variables to understand the concept of getting values inside blade templates.

Let’s say we want to fetch the value of APP_NAME.

Example #1 – Using env() Helper Function

Inside blade template you can use env() helper function to get access env values.

<h3>{{ env('APP_NAME') }}</h3>

Output

Online Web Tutor

Also, we can use this env variable values inside laravel directives.

@if(env('APP_ENV') == 'local')
       Match
@endif

Additionally, you can use the env values inside script tags.

<script>

var name = "{{ env('APP_NAME') }}";

console.log(name);

</script>

Example #2 – Using config() Helper Function

Here, we will use config() helper function of laravel. It returns the env variable value.

{{ config('app.name') }}

app.name means APP_NAME.

For LOG_CHANNEL, it will be like log.channel

We hope this article helped you to How to Get env Variable in Laravel 9 Blade Templates Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5