Link to the repository
[Only for premium members]
[Only for premium members]
Before switching to the setup of multiple databases, let's talk about WHY you would want to do that.
I got this question from a few people on Twitter:
A multi-database setup means one database per customer/company/organization. Yes, it means managing 100s of databases if you have 100s of companies using your application.
Sounds overwhelming, doesn't it? But not necessarily.
The most common use case for this is the BUSINESS needs by those companies to store data separately from other companies using your application. Usually for privacy and legal reasons.
For example, if you are Microsoft, you would probably want to minimize the risks that some of your internal data would become visible to Apple or Google?
Also, there may be technical architectural reasons to separate the database, such as potential individual scaling or managing resources for each tenant based on their own requirements.
However, it also comes with additional complexity and more work to set up and manage multiple databases.
Let me try to summarize the pros and cons of this multi-database approach.
Advantages of multiple databases:
Disadvantages:
In short, you need a multi-database setup only if it's actually the requirement either from the clients or from yourself as an architectural decision for scalability.
In most cases, for smaller projects, one database is totally fine.
That said, if you still want to dive into that more complex setup, let's get familiar with the approach and the tools.
Let's first create the multi-database and multi-tenancy setup with the package stancl/tenancy. Some of the code from earlier for this package from a single database, like installation, will be repeated, and then we'll move deeper.
The initial setup is the same Laravel Breeze with two CRUDs: Projects and Tasks.
So, let's install the package.
composer require stancl/tenancyphp artisan tenancy:install
bootstrap/providers.php:
return [ App\Providers\AppServiceProvider::class, App\Providers\TenancyServiceProvider::class, ];
IMPORTANT NOTICE: Version 3 doesn't support the
database
session driver. The easiest change would be tofile
as a session driver.
And now, here is the first difference between single and multiple databases. The DB_CONNECTION
value should be...