Set Up the Database Configuration File: Laravel’s database configuration is stored in the config/database.php
file. This file contains settings for all supported database systems, such as MySQL, SQLite, PostgreSQL, and SQL Server.
Configure .env
File: Laravel uses the .env
file to store sensitive environment-specific settings, such as database credentials. By default, you’ll find the database configuration section in the .env
file.
Example:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
Configure Database Settings in config/database.php
: In config/database.php
, Laravel reads the values from the .env
file and applies them. It’s important to ensure that the default connection matches the one defined in your .env
file.
Example:
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
],
],
Testing the Database Connection: After configuring the .env
and config/database.php
files, test the connection by running a simple database query or using Artisan commands.
Example: You can run this command to ensure that the connection is working properly:
php artisan migrate
Switching Between Database Connections: Laravel allows you to easily switch between different database connections. If you need to use a different connection for certain operations, you can specify it dynamically.
Example:
DB_CONNECTION=sqlite
DB_DATABASE=/path_to_your_database/database.sqlite
Using SQLite or Other Databases: Laravel also supports other databases like SQLite, PostgreSQL, and SQL Server. You can configure these by simply modifying the .env
file and adjusting the settings in config/database.php
.
Example for SQLite:
DB_CONNECTION=sqlite
DB_DATABASE=/path_to_your_database/database.sqlite
Laravel makes database configuration simple through the .env
file and config/database.php
. By following these steps, you can configure your database connection, test it, and switch between different connections as needed for your application. This flexibility ensures smooth database management in Laravel.