Laravel Database Configuration: .env Setup Guide
19 May 2025 | Category: Laravel
Configuring the database in Laravel is a critical step to connect your application to a database system such as MySQL, PostgreSQL, SQLite, or SQL Server. The primary configuration is handled in the .env
file, which stores environment-specific settings like database credentials. This SEO-friendly, plagiarism-free guide explains how to set up the .env
file for database configuration in Laravel, including examples for different database systems and best practices. Based on Laravel 11 (as of May 19, 2025), this tutorial is tailored for beginners and intermediate developers.
What is the .env File?
The .env
file, located in the root of your Laravel project, contains key-value pairs for environment-specific configuration, including database settings. It is loaded during application bootstrapping and should not be committed to version control (use .env.example
as a template). The .env
file allows you to define database credentials securely and switch between different database systems easily.
Default .env Database Settings
When you create a new Laravel project, the .env
file includes default database settings:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
- DB_CONNECTION: Specifies the database driver (
mysql
,pgsql
,sqlite
,sqlsrv
). - DB_HOST: The database server address (e.g.,
127.0.0.1
for localhost). - DB_PORT: The port used by the database (e.g.,
3306
for MySQL). - DB_DATABASE: The name of the database.
- DB_USERNAME: The database user.
- DB_PASSWORD: The user’s password (leave empty if none).
These settings are used by config/database.php
to establish a database connection.
Setting Up the .env File for Different Databases
Laravel supports multiple database systems out of the box. Below are step-by-step instructions for configuring the .env
file for common databases.
1. MySQL
MySQL is one of the most popular databases used with Laravel.
Example .env Configuration:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=secret
Steps:
- Install MySQL: Ensure MySQL is installed and running on your system.
- Create a Database:
- Use a tool like phpMyAdmin, MySQL Workbench, or the MySQL CLI:
sql CREATE DATABASE myapp;
- Update .env:
- Set
DB_DATABASE
to the database name (myapp
). - Set
DB_USERNAME
andDB_PASSWORD
to your MySQL user credentials.
- Verify Connection: Ensure the MySQL server is running on the specified host and port.
2. PostgreSQL
PostgreSQL is a powerful, open-source relational database.
Example .env Configuration:
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=myapp
DB_USERNAME=postgres
DB_PASSWORD=secret
Steps:
- Install PostgreSQL: Ensure PostgreSQL is installed and running.
- Create a Database:
- Use the
psql
CLI or a GUI tool like pgAdmin:sql CREATE DATABASE myapp;
- Update .env:
- Set
DB_CONNECTION
topgsql
. - Set
DB_DATABASE
,DB_USERNAME
, andDB_PASSWORD
as needed. - Adjust
DB_HOST
andDB_PORT
if different (default port is5432
).
- Install PHP Extension: Ensure the
pdo_pgsql
PHP extension is enabled.
3. SQLite
SQLite is a lightweight, file-based database ideal for development or small applications.
Example .env Configuration:
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
Steps:
- Create a Database File:
- Create an empty SQLite database file:
bash touch database/database.sqlite
- Ensure the file is writable by the web server.
- Update .env:
- Set
DB_CONNECTION
tosqlite
. - Set
DB_DATABASE
to the absolute path of the.sqlite
file (e.g.,/var/www/myapp/database/database.sqlite
). - Remove other settings (
DB_HOST
,DB_PORT
,DB_USERNAME
,DB_PASSWORD
) as they are not needed.
- Verify Permissions: Ensure the Laravel application has read/write access to the file.
4. SQL Server
SQL Server is commonly used in enterprise environments.
Example .env Configuration:
DB_CONNECTION=sqlsrv
DB_HOST=127.0.0.1
DB_PORT=1433
DB_DATABASE=myapp
DB_USERNAME=sa
DB_PASSWORD=secret
Steps:
- Install SQL Server: Ensure SQL Server is installed and accessible.
- Create a Database:
- Use SQL Server Management Studio or a similar tool to create the database.
- Update .env:
- Set
DB_CONNECTION
tosqlsrv
. - Configure
DB_DATABASE
,DB_USERNAME
, andDB_PASSWORD
. - Adjust
DB_HOST
andDB_PORT
(default is1433
).
- Install Drivers: Install PHP’s SQL Server drivers (
sqlsrv
andpdo_sqlsrv
) and configure them.
5. Multiple Database Connections
You can configure multiple databases by defining additional connections in config/database.php
and referencing them in .env
.
Example .env:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=secret
DB_BACKUP_CONNECTION=mysql
DB_BACKUP_HOST=127.0.0.1
DB_BACKUP_PORT=3306
DB_BACKUP_DATABASE=myapp_backup
DB_BACKUP_USERNAME=root
DB_BACKUP_PASSWORD=secret
Update config/database.php:
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
],
'mysql_backup' => [
'driver' => 'mysql',
'host' => env('DB_BACKUP_HOST', '127.0.0.1'),
'port' => env('DB_BACKUP_PORT', '3306'),
'database' => env('DB_BACKUP_DATABASE', 'backup'),
'username' => env('DB_BACKUP_USERNAME', 'root'),
'password' => env('DB_BACKUP_PASSWORD', ''),
],
],
Usage:
- Specify the connection in a model:
class Post extends Model
{
protected $connection = 'mysql_backup';
}
- Or in a query:
$posts = DB::connection('mysql_backup')->table('posts')->get();
Verifying the Database Connection
To ensure your database configuration is correct:
- Check Server: Verify the database server is running and accessible.
- Test with Tinker:
php artisan tinker
>>> DB::connection()->getPdo();
- Success: Returns a PDO object.
- Failure: Throws an error (e.g., “Connection refused” or “Database does not exist”).
- Run a Migration:
php artisan migrate
- If migrations run without errors, the connection is working.
- Check Logs: Review
storage/logs/laravel.log
for connection errors.
Best Practices for .env Database Configuration
- Secure the .env File:
- Add
.env
to.gitignore
to prevent committing sensitive credentials. - Set file permissions to
600
(owner read/write only):bash chmod 600 .env
- Use strong, unique passwords in production.
- Use Environment Variables in Production:
- Instead of
.env
, configure database settings via server environment variables (e.g., in Apache or Docker) for added security.
- Validate Credentials:
- Ensure the database user has appropriate permissions (e.g.,
SELECT
,INSERT
,UPDATE
,DELETE
for the database).
- Keep .env.example Updated:
- Maintain a
.env.example
file with placeholder values for team members or deployment. - Example:
env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database DB_USERNAME=your_username DB_PASSWORD=your_password
- Clear Config Cache:
- After updating
.env
, clear the configuration cache:bash php artisan config:clear
- Use Appropriate Drivers:
- Ensure PHP extensions are installed for your database (e.g.,
pdo_mysql
for MySQL,pdo_pgsql
for PostgreSQL).
- Backup Regularly:
- Schedule backups for production databases to prevent data loss.
Common Issues and Debugging
- “Access denied for user”:
- Verify
DB_USERNAME
andDB_PASSWORD
in.env
. - Ensure the user has permissions for the database.
- “No such database”:
- Confirm
DB_DATABASE
exists (create it if necessary). - “Connection refused”:
- Check if the database server is running.
- Verify
DB_HOST
andDB_PORT
are correct. - SQLite “Database does not exist”:
- Ensure the
.sqlite
file exists and the path is absolute. - Check file permissions.
- Cached Configuration:
- Run
php artisan config:clear
to refresh.env
changes. - Logs:
- Check
storage/logs/laravel.log
for detailed error messages.
Example: Complete .env Setup Workflow
Step 1: Set Up MySQL
- Install MySQL and create a database:
CREATE DATABASE myapp;
- Update
.env
:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=secret
Step 2: Test the Connection
php artisan tinker
>>> DB::connection()->getPdo();
- If successful, proceed to migrations or other database tasks.
Step 3: Secure the .env File
chmod 600 .env
- Ensure
.env
is in.gitignore
.
Step 4: Create a Migration (Optional)
To confirm the setup, create and run a migration:
php artisan make:migration create_posts_table
Migration File:
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Run:
php artisan migrate
Conclusion
Configuring the database in Laravel via the .env
file is straightforward and flexible, supporting multiple database systems like MySQL, PostgreSQL, SQLite, and SQL Server. By correctly setting up the .env
file, verifying the connection, and following security best practices, you can ensure a robust database integration for your Laravel application. This setup is the foundation for migrations, models, and other database-related tasks.
Next Steps:
- Update your
.env
file with your database credentials. - Test the connection using
php artisan tinker
. - Create a migration to define your database schema.
For further learning, explore Laravel’s official documentation or connect with the Laravel community on platforms like X. Start configuring your Laravel database today!
Laravel .env Database Configuration Example
This artifact provides practical examples of .env
configurations for different database systems in Laravel.
MySQL Configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=secret
PostgreSQL Configuration
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=myapp
DB_USERNAME=postgres
DB_PASSWORD=secret
SQLite Configuration
DB_CONNECTION=sqlite
DB_DATABASE=/var/www/myapp/database/database.sqlite
SQL Server Configuration
DB_CONNECTION=sqlsrv
DB_HOST=127.0.0.1
DB_PORT=1433
DB_DATABASE=myapp
DB_USERNAME=sa
DB_PASSWORD=secret
Multiple Database Connections
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=secret
DB_BACKUP_CONNECTION=mysql
DB_BACKUP_HOST=127.0.0.1
DB_BACKUP_PORT=3306
DB_BACKUP_DATABASE=myapp_backup
DB_BACKUP_USERNAME=root
DB_BACKUP_PASSWORD=secret
Usage
- Choose the appropriate configuration for your database system.
- Create the database (if applicable) using a database management tool or CLI.
- Update the
.env
file in your Laravel project root with the selected configuration. - Ensure the database server is running and accessible.
- Test the connection:
php artisan tinker
>>> DB::connection()->getPdo();
- Secure the
.env
file:
chmod 600 .env
- Ensure
.env
is listed in.gitignore
.
This example covers common database systems and demonstrates how to configure multiple connections, providing a solid foundation for Laravel database setup.