How7o
  • Home
  • Marketing
    MarketingShow More
  • OS
    OSShow More
    How to force quit frozen apps in Ubuntu
    Force Close an App in Ubuntu (xkill, System Monitor, kill -9)
    4 Min Read
  • Features
    FeaturesShow More
  • Guide
    GuideShow More
  • Contact
  • Blog
Reading: How to Get .env Variables in Laravel (Controller + Blade) Safely
Share
Subscribe Now
How7oHow7o
Font ResizerAa
  • Marketing
  • OS
  • Features
  • Guide
  • Complaint
  • Advertise
Search
  • Categories
    • Marketing
    • OS
    • Features
    • Guide
    • Lifestyle
    • Wellness
    • Healthy
    • Nutrition
  • More Foxiz
    • Blog Index
    • Complaint
    • Sitemap
    • Advertise
Follow US
Copyright © 2014-2023 Ruby Theme Ltd. All Rights Reserved.
How7o > Blog > Uncategorized > How to Get .env Variables in Laravel (Controller + Blade) Safely
Uncategorized

How to Get .env Variables in Laravel (Controller + Blade) Safely

how7o
By how7o
Last updated: February 6, 2026
4 Min Read
get .env variable in Laravel using env and config
SHARE

I recently needed to get .env variable in Laravel while moving some settings into my project’s .env file. I added a couple of custom keys and then got stuck on the “where do I read these from?” part—Blade, controller, both?

Contents
  • Example .env variables
  • Option 1: Use env() (quick, but not ideal for production)
    • Controller example (using env())
    • Blade example (using env())
  • Option 2: Recommended — map env values into config, then use config()
    • Step 1: Create a config file
    • Step 2: Read values in a controller with config()
    • Step 3: Read values in Blade with config()
  • Step-by-step checklist
  • Troubleshooting
    • 1) My value is always null
    • 2) It works locally but not on production
    • 3) Should I display secrets in Blade?
  • Official docs (worth bookmarking)
  • Related guides

The short answer is: yes, you can read them using env(). But the “works now, breaks later” issue shows up when config caching is enabled. So in this post, I’ll show the quick method and the production-safe method I actually use.

Example .env variables

Here’s a simple example of custom values in .env:

APP_KEY="pufimebradr481u3it9l"
APP_SECRET="tr1wu7lyujupr8truperojuhlxedu81a"

Now let’s access them from a controller and a Blade view—cleanly.

Option 1: Use env() (quick, but not ideal for production)

Laravel includes the env() helper, and it works in both controllers and Blade templates.

Controller example (using env())

public function index()
{
    if (env('APP_SECRET')) {
        // do something with the APP_SECRET
    }

    $secret = env('APP_SECRET', 'default-secret');

    return view('welcome', compact('secret'));
}

Blade example (using env())

@if (env('APP_KEY'))
    Key is set
@endif

Value: {{ env('APP_SECRET') }}

Important: This is where many projects get tripped up. When you run php artisan config:cache (common in production), Laravel’s own guidance is to avoid calling env() directly throughout your app. The safer pattern is to read env values in config files and use config() everywhere else.

Option 2: Recommended — map env values into config, then use config()

This is the method I switched to because it stays reliable across environments and deployments.

  • Put env() calls in a config file (this is the intended place)
  • Use config() in controllers, services, jobs, and Blade views

Step 1: Create a config file

Create config/custom.php:

<?php
return [
    'app_key' => env('APP_KEY'),
    'app_secret' => env('APP_SECRET'),
];

You can name the file anything, but a dedicated custom.php keeps it tidy for project-specific settings.

Step 2: Read values in a controller with config()

Now access them like this:

public function index()
{
    $key = config('custom.app_key');
    $secret = config('custom.app_secret');
    // Example usage
    if (!empty($secret)) {
        // do something secure here
    }
    return view('welcome', compact('key', 'secret'));
}

Step 3: Read values in Blade with config()

And in your Blade file:

@if (config('custom.app_key'))
    Key is set
@endif
Value: {{ config('custom.app_secret') }}

That’s it. This approach is the most consistent way to get .env variable in Laravel without surprises later.

Step-by-step checklist

  1. Add your keys to .env (example: APP_SECRET=...).
  2. Create config/custom.php and map env values using env().
  3. Use config('custom.app_secret') in controllers and Blade.
  4. If you cache config in production, rebuild the cache after changes.

Troubleshooting

1) My value is always null

  • Double-check the key name matches exactly (case-sensitive): APP_SECRET vs APP_Secret.
  • Avoid extra spaces around =. Use APP_SECRET=value (not APP_SECRET = value).
  • If you moved to config(), make sure your config key path is correct: config('custom.app_secret').

2) It works locally but not on production

This is usually config caching. After updating .env on the server, run:

php artisan config:clear
php artisan cache:clear
php artisan config:cache

Then prefer reading values via config() throughout your app.

3) Should I display secrets in Blade?

Usually, no. If it’s a real secret (API keys, private tokens), keep it server-side. Only pass non-sensitive values to views, and never print secrets into HTML output.

Official docs (worth bookmarking)

  • Laravel Configuration (env and config)
  • Laravel Helpers (including env())

Related guides

Add your internal links here when available:

  • How to use Laravel config caching safely
  • Best practices for managing secrets in Laravel

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article How to use localStorage in JavaScript shown in a browser storage panel How to Use localStorage in JavaScript (With Real Examples + Troubleshooting)
Next Article CSS page break for printing shown in a print preview layout CSS Page Break for Printing: How to Split a Web Page Into Multiple Printed Pages
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!
Most Popular
Find prime numbers in JavaScript thumbnail
How to Find Prime Numbers in JavaScript (1 to 100) — Fast & Simple Methods
February 6, 2026
Dynamically set site title and tagline in WordPress by country
How to Dynamically Set Site Title and Tagline in WordPress (By Country)
February 6, 2026
Capitalize all words in JavaScript with a ucwords-style function
Capitalize All Words in JavaScript (ucwords Equivalent) + First Letter Uppercase
February 6, 2026
CSS page break for printing shown in a print preview layout
CSS Page Break for Printing: How to Split a Web Page Into Multiple Printed Pages
February 6, 2026
get .env variable in Laravel using env and config
How to Get .env Variables in Laravel (Controller + Blade) Safely
February 6, 2026

You Might Also Like

Add commas to numbers in PHP using number_format()
Uncategorized

How to Add Commas to Numbers in PHP (Thousands Separator)

5 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Latest News

  • SEO Audit Tool
  • Client ReferralsNew
  • Execution of SEO
  • Reporting Tool

Resouce

  • Google Search Console
  • Google Keyword Planner
  • Google OptimiseHot
  • SEO Spider

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?