Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for naming additional database connections #54162

Draft
wants to merge 1 commit into
base: 11.x
Choose a base branch
from

Conversation

JanneDeVos
Copy link
Contributor

This pull request introduces the ability to name multiple database connections, improving the developer experience when working with multiple databases. By providing meaningful names for each connection, it becomes more intuitive to switch between different databases.

This feature adds an abstraction layer that decouples the database implementation from your code by allowing you to define multiple named connections in the database configuration:

/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/

'default' => env('DB_CONNECTION', 'sqlite'),
'other' => env('DB_CONNECTION_OTHER', 'mysql'),

Models can then specify which connection to use via the $connection property:

class Order extends Model
{
    protected $connection = 'other'; // Equals to mysql

Or you can use the connection directly in queries:

$orders = DB::connection('other')->table('orders')->get();

Copy link

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

@shaedrich
Copy link
Contributor

shaedrich commented Jan 11, 2025

What's wrong with naming additional connections under database.connections?

https://github.com/laravel/laravel/blob/f9bedb320cac1c77d78052c1355ea37709cd464b/config/database.php#L32-L113

There is already is a $connection property that can take connection names:

/**
* The connection name for the model.
*
* @var string|null
*/
protected $connection;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants