Configuration

Understanding the .env File and Database Connection in Laravel

7 min read · By the GudangCode Team

Almost every "the app won't run" problem after downloading source code traces back to a single file: .env. This file stores settings that differ between environments (your machine, the production server), so they must never be hardcoded. Understanding it makes you far faster at fixing errors.

Why .env Is Separate from Code

Database credentials and secret keys differ everywhere. By keeping them in .env, the same code runs on your laptop, a staging server, and production without changes. That is why .env is never committed to Git (it is in .gitignore), and you are given .env.example as a template.

Application Lines

APP_NAME="My App"
APP_ENV=local
APP_KEY=base64:xxxxxxxxxxxxxxxxxxxxxxxx
APP_DEBUG=true
APP_URL=http://127.0.0.1:8000
  • APP_KEY must be filled — run php artisan key:generate.
  • APP_ENV = local while developing, production when live.
  • APP_DEBUG = true shows detailed errors (great while tinkering) but must be false in production to avoid leaking sensitive information.
  • APP_URL affects links, assets, and emails. Set it to the real domain in production.

Database Lines

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_app
DB_USERNAME=root
DB_PASSWORD=

This is the part that goes wrong most often. Note that:

  • DB_DATABASE must already exist — Laravel does not create the database automatically, only its tables.
  • On many local installs, DB_USERNAME=root and DB_PASSWORD is empty. In production, use a dedicated user with a strong password.
  • With a custom socket (some macOS setups), DB_HOST may need to be localhost instead.

After Changing .env, Clear the Cache

Laravel often caches configuration. If your .env change seems to have no effect, run:

php artisan config:clear
php artisan cache:clear

In production it is the reverse — you run php artisan config:cache to speed the app up, but remember to repeat it every time .env changes.

Testing the Database Connection

The easiest way to confirm the connection is to run a migration:

php artisan migrate

If you see "SQLSTATE[HY000] [1045] Access denied", the username/password is wrong. If you see "Unknown database", the database name in .env does not match or has not been created. These error messages are actually helpful — read them calmly, because they almost always point to a specific .env line.

Other Commonly Used Lines

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
FILESYSTEM_DISK=public
QUEUE_CONNECTION=database

For development, services like Mailtrap capture test emails so nothing is really sent. Once you understand this map, the .env file turns from a source of confusion into a control panel you own.


Tim Support
Online
Isi data dulu untuk mulai chat:
Beri rating & testimoni sebelum menutup:
Live chat by gudangcode.com