Database Configuration
Before Doctrine's EntityManager (covered on the previous
Doctrine ORM page) can persist or fetch anything, Symfony
needs to know how to connect to your actual database. That connection is configured through a
single environment variable: DATABASE_URL.
The DATABASE_URL Variable
Symfony's .env file defines environment variables for the application, and
Doctrine reads its connection details from DATABASE_URL in a standard connection
string format:
DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name"
Reading that string left to right: the driver (mysql), then the username and
password, then the host and port the database server is listening on, and finally the database
name itself. Doctrine parses this one string into everything it needs to open a connection.
.env vs. .env.local
| File | Purpose | Committed to Git? |
|---|---|---|
.env | Default/placeholder values, shared with every developer | Yes |
.env.local | Real, machine-specific values — including database credentials | No — gitignored by default |
The committed .env file holds a generic placeholder DATABASE_URL —
enough to document the expected format, but not a real password. .env.local, which
Symfony automatically loads on top of .env and overrides matching keys, is where you
put your actual credentials. This is the same underlying idea as CakePHP's split between
app.php and app_local.php: one file is generic and safe to share, the
other holds real secrets and never leaves your machine. Since .env.local is
gitignored, every developer and every environment (local, staging, production) keeps its own
copy with its own real values, while the committed .env stays free of anything
sensitive.
.env. If a secret ever does get committed, rotating the credential is the only real fix — removing it from a later commit doesn't erase it from the repository's history.Creating the Database
On a brand-new project, the database itself may not exist yet. Symfony's console command
creates it for you, based on the database name in DATABASE_URL:
php bin/console doctrine:database:create
You typically only need to run this once, the first time you set up a project on a new machine.
Running Migrations
Once the database exists, its tables still need to match your entity mappings. The migration
files generated with make:migration (see the Doctrine
ORM page) contain the SQL needed to bring the schema up to date — running them applies that
SQL:
php bin/console doctrine:migrations:migrate
This command runs any migration files that haven't been applied yet, in order, and records which ones it has already run so it never re-applies the same migration twice. Run it every time you pull new migration files — for example, after a teammate adds a new entity or changes an existing one.