Learn how to configure a database connection in Laravel and perform CRUD operations using Eloquent ORM or the database query builder. In this Laravel database configuration tutorial, we'll walk you through the steps of setting up a database connection in the .env file.
Steps to Configure Database in Laravel
Laravel uses the PDO (PHP Data Objects) extension to connect to databases. To configure your database in Laravel, you will need to update the config/database.php file with your database credentials.
- First, ensure you have a database set up and have the credentials (username, password, hostname, etc.) ready. Laravel supports several database systems, including MySQL, PostgreSQL, and SQLite.
- Open the
config/database.phpfile and find theconnectionsarray. This array contains all of the available connection configurations. - Choose a connection type from the array (e.g.,
mysql,sqlite,pgsql, etc.) and update the corresponding configuration options with your database credentials. For example, to configure a MySQL database, you might update the Default Database Connection Name:'default' => env('DB_CONNECTION', 'mysql'), - Open the
.envfile in the root directory of your Laravel project. Set theDB_CONNECTIONvariable in this file to match the connection type you chose in the previous step. For example, if you are using a MySQL database, you would set theDB_CONNECTIONvariable tomysql.DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD= - Set the
DB_HOSTvariable to the hostname of your database server. For example, if you are using a local development server, you might set this tolocalhost. - Set the
DB_DATABASEvariable to the name of your database. - Set the
DB_USERNAMEandDB_PASSWORDvariables to the username and password for your database. - If you use a MySQL or PostgreSQL database, you may need to set the
DB_PORTvariable in your.envfile to the correct port number for your database server. - If you use a MySQL database, you may also need to set the
DB_SOCKETvariable in your.envfile if your MySQL server uses a socket other than the default. - Save the
.envfile and exit.
Once you have configured your database connection, you can use the Laravel query builder or Eloquent ORM to perform CRUD operations on your database.
For example, to retrieve all rows from a table called users, you could use the following code:
Example:
$users = DB::table('users')->get();