change database connection in laravel model
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Title: Easily Change Database Connection in Laravel Model for External Database Access
Body:
Laravel is known for its extensive database management capabilities, but sometimes you may need to work with an external database for specific models or situations. In this comprehensive blog post, we'll guide you through the process of changing the database connection in your Laravel 4.2 model to access an external database, complete with relevant code examples and best practices.
First, let's take a look at the general structure of your existing model:
```php
increments('id');
$table->string('name');
// add other fields as needed
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('agencies');
}
}
```
Run the migration:
```bash
php artisan migrate
```
Finally, create a new test file (e.g., test_external_db_access.php) to check your model's interaction with the external database:
```php
get();
// Ensure you're getting results from the external database
$this->assertTrue($result->count() > 0);
}
}
```
Run your test suite and make sure everything is working as expected.
Conclusion:
With these steps, you have successfully changed your Laravel 4.2 model to use an external database for its table. By defining the database connection settings in .env and updating the model's configuration accordingly, you can easily interact with multiple databases from within your Laravel application. Remember to always follow best practices and keep your database connections secure. Enjoy working with your external database!