In this episode, we're tackling environment variables and .env
files—basically, how to move your app's config (like app name, debug status, etc.) out of your code and into a separate, secret file. This is super helpful for keeping things like API keys or environment-specific settings out of source control and letting you easily change them between your local dev machine and production.
We start by explaining why you shouldn't hardcode config into your app, and how a .env
file lets you keep things flexible and secure. Then, we set up a .env
in the root of our project, add some values (like APP_NAME
and APP_DEBUG
), and make sure it's ignored by git so it doesn't get pushed up with your code.
Next, we install a PHP package to read our .env
file, so we can load those environment variables in our app. We wire this up in our bootstrap process, making them available everywhere. Then, we show how to fetch these values in your config (using a helper method), and why that's a better approach than hardcoding.
We also look at contextually enabling stuff based on your environment—like only turning on your fancy error pages if debugging is enabled, but hiding them from real users in production. There's a live test breaking the app to see error handling in action, toggling between dev and production settings in the .env
file.
By the end, you'll have your app reading config from .env
, so it's much easier to manage and way safer!