Laravel 5 : Use different database for testing and local
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Laravel makes it easy to manage databases by allowing you to connect to multiple database connections. This convenient feature can be particularly useful when working on both development and testing environments where different database needs may arise. In this comprehensive guide, we'll walk through how to configure your Laravel application to use separate databases for development and testing without editing the .env file each time.
Creating Separate Database Connections
Start by creating two database connections in your config/database.php file, one for development and another for testing. In this example, let's imagine using a PostgreSQL connection for development and MySQL for testing:
Now, we'll create a separate .env file for each environment. Name these files according to your preference (e.g., .env.development, .env.test) and place the database connection credentials in their respective files.
Configuring Laravel to Use Custom Database Connections
Next, we'll modify the bootstrap/app.php file to load the correct .env file based on the environment. This can be done using the following code:
This ensures that your Laravel application will load the appropriate database connection based on the environment. For example, if you are working on the development environment, your .env file should point to the 'mysql-dev' connection.
Switching Database Connections Automatically
Lastly, we can use Laravel's built-in phpunit to run database migrations and seeds according to your environment by setting the APP_ENV variable. You can do this by running the following commands:
This way, your Laravel application will load the correct database connection for development and testing without the need to edit any .env files.
Conclusion:With this guide, you can easily switch between multiple database connections in your Laravel 5 application according to the environment. By creating separate database connections for development and testing, you'll have a more efficient setup that allows for better testing and development practices without the hassle of editing .env files every time.