How to set up a database connection in Symfony?

To set up a database connection in Symfony, follow these steps:

  1. Open your Symfony project and navigate to the .env file in the root directory.

  2. Look for the DATABASE_URL variable in the .env file. This variable contains the connection string for your database. It should look something like this:

DATABASE_URL=mysql://db_user:[email protected]:3306/db_name
  1. Replace db_user, db_password, and db_name with your actual database username, password, and name.

  2. Next, open the config/packages/doctrine.yaml file in your Symfony project.

  3. Check if the doctrine configuration is set up correctly. It should look like this:

doctrine: dbal: url: '%env(resolve:DATABASE_URL)%'
  1. Make sure the url parameter is set to %env(resolve:DATABASE_URL)%, which refers to the DATABASE_URL variable in the .env file.

  2. Save the changes to the .env and doctrine.yaml files.

  3. Finally, run the following command in the terminal to create the database schema based on your entity classes:

php bin/console doctrine:schema:update --force

This will set up the database connection in Symfony and create the necessary tables based on your entity classes. You can now start using the database in your Symfony project.