In Laravel, put secrets in the .env file, expose them to the app through a config file with env('NAME'), and read them elsewhere with config('services.name.key'). Do not commit .env. Calling env() outside config files breaks once you cache configuration for production.
Read the key from the environment
// config/services.php
return [
'stripe' => [
'secret' => env('STRIPE_SECRET_KEY'),
],
];
// anywhere in the application
$apiKey = config('services.stripe.secret');Local development
Laravel creates .env from .env.example and git-ignores it. Keep only development keys there. For team sharing, Laravel can encrypt environment files with php artisan env:encrypt, producing a file you can commit and decrypt with env:decrypt using a key kept elsewhere. Do not leave APP_DEBUG=true on a server, because the error page can display environment information.
Production
In production run php artisan config:cache for speed, and set real environment variables from your host's secret store or a deployment tool. After caching, the .env file is no longer loaded, so env() called outside config files returns null: read values through config(). Rotate APP_KEY carefully, since it encrypts cookies and stored data.
Mistakes to avoid
- Calling
env()in controllers or models; afterconfig:cacheit returns null, so move it intoconfig/*.php. - Committing
.envor leavingAPP_DEBUG=truein production, which can expose configuration on error pages. - Serving the project root as the web root so that
/.envis downloadable; point the web server atpublic/. - Changing
APP_KEYwithout a plan, which invalidates encrypted values and sessions.
When an AI agent works on your PHP (Laravel) project
Coding agents run inside your project folder, so they can read the same .env file your app reads. BotPassword injects keys at run time instead: the agent calls the run_with intent through the MCP server and the process gets the variables it needs while the agent sees only redacted output. Planned: bpw run, a CLI form of the same.
Frequently asked questions
Why does env() return null in Laravel?
After php artisan config:cache, Laravel stops loading .env, so env() only works inside config files. Read values with config('file.key') elsewhere.
Is Laravel's .env file safe to commit?
No. Commit .env.example, or use php artisan env:encrypt to produce an encrypted file you can commit, and keep the decryption key outside the repository.
Should I keep API keys in a .env file for PHP (Laravel)?
A .env file that is git-ignored is fine for local development, but every process and every AI coding agent running in that folder can read it. Load secrets into the environment at run time from a password manager or secrets manager instead, so no plaintext file sits in the project.