Laravel Tutorial Index

Database Management

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.

  1. 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.
  2. Open the config/database.php file and find the connections array. This array contains all of the available connection configurations.
  3. 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'),
  4. Open the .env file in the root directory of your Laravel project. Set the DB_CONNECTION variable 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 the DB_CONNECTION variable to mysql.
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=laravel
    DB_USERNAME=root
    DB_PASSWORD=
  5. Set the DB_HOST variable to the hostname of your database server. For example, if you are using a local development server, you might set this to localhost.
  6. Set the DB_DATABASE variable to the name of your database.
  7. Set the DB_USERNAME and DB_PASSWORD variables to the username and password for your database.
  8. If you use a MySQL or PostgreSQL database, you may need to set the DB_PORT variable in your .env file to the correct port number for your database server.
  9. If you use a MySQL database, you may also need to set the DB_SOCKET variable in your .env file if your MySQL server uses a socket other than the default.
  10. Save the .env file 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();


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram