I
I
Ivan Vovchok2020-01-24 19:09:35
Laravel
Ivan Vovchok, 2020-01-24 19:09:35

How to set up work with two bases on Laravel?

Hello!
The challenge is to divide all application users into two groups, say "Russians" and "Americans", with two separate databases. Depending on which group the user belongs to, output data from the corresponding database. The group itself is defined in the table usersfor each user separately.
In the file config/database.php, I added a new connection for the second database.
The output of all data for the user is processed through the controllers. I tried to use group membership check and return data via DB::connection,but inside the controller it doesn't work. DB::defined as a controller that is not initialized.
Is there a way at the time of user authorization to determine his group and, depending on it, immediately establish the necessary connection to the required database on a permanent basis for this user? I have read that this seems to be possible via IoC, but I have no idea how this is done.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daria Motorina, 2020-01-24
@Vanovich

...inside the controller it doesn't work. DB:: is defined as a controller that is not initialized.

The DB class needs to be imported with the correct namespace, in this case you need to write \DB::connection(...).
If the division into two databases is your technical decision, then I advise you to think it over again, because now this division sounds unjustified from a technical point of view (why can't you normalize / denormalize data and just store them in separate tables in one database).

A
Andrey, 2020-01-24
@VladimirAndreev

0. Transfer users to a separate database
1. Configure 3 different connections - to the database of users, for Russians, for Americans
2. In the model constructor (except for users), get the group and define the $connection property of the model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question