DEV Community

Cover image for Using Configs in Laravel 8
Graham Morby
Graham Morby

Posted on

2

Using Configs in Laravel 8

One of the biggest things we do in modern web development is to consume API's and with that comes lots of keys, secrets, and config points. With that comes issues, now up until recently I would store the needed key etc in my .env and call it direct! Which worked and worked well.

So let's say we have a support email that is used in many places, we store that in the .env file we call it.

MAIL_SUPPORT_ADDRESS: "support@grahammorbydev.com"
Enter fullscreen mode Exit fullscreen mode

We grab that in blade or a controller as so

env('MAIL_SUPPORT_ADDRESS')
Enter fullscreen mode Exit fullscreen mode

Which works just fine, but let's say you go into production, do not update your .env, and load the site? What will happen? That page will error that the address doesn't exist or the support email will not work. Now, this is a really basic use case for config, but I hope it will allow you to see the benefit.

So what we do is head over to the config folder and create a new file called contact.php. if we then add the following code

<?PHP
return => [
     'email' => env('MAIL_SUPPORT_ADDRESS', 'help@grahammorbydev.com')
]
Enter fullscreen mode Exit fullscreen mode

Then in my blade file or controller, I just use

config('contact.email');
Enter fullscreen mode Exit fullscreen mode

This allows me to use any value I set in my env or fallback should I forget and that's just the start. There are tons of other things you can do to allow you to write cleaner code and give you the edge in Laravel!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay