Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aurorame's avatar

How i can made rule for API?

I try to make API that receive data from 4 different connection which have same 5 databases, totally: connection1 = db1, db2, db3, db4,db5 connection2 = db6, db7, db8, db9, db10 connection3 = db11, db12, db13, db14, db15 connection4 = db16, db17, db18, db19, db20 All routes of API required string "data" in request which mean db`s to receive data. How i can make rules for all API routes that mean: If $request->input('data') == 1 that we connect to connection1->db1 if $request->input('data') == 13 that we connect to connection3->db13

0 likes
12 replies
Sinnbeck's avatar

What is the purpose of so many different databases? Each customer has their own or?

aurorame's avatar

@Sinnbeck technical necessity. Unfortunately, I can't change it, I need to work with it

Sinnbeck's avatar

@aurorame ok. Did you try setting the database like I suggested in the previous post of yours?

You can also try using the query builder

$query = DB::connection($connection)->table($database. '.users')->where(... 
aurorame's avatar

@Sinnbeck how can i use query builder here? return new DataResource(Data::where('Name', $request->input('name'))->firstOrFail()); That code used in DataController, DataResource - resources, Data:: - model

Sinnbeck's avatar

@aurorame use the db facade as you are setting everything dynamically. It might be possible to set the database on the model at runtime, but I would need to dig into the source to find it

Sinnbeck's avatar

Did some digging and perhaps you can do it with ->setTable($db. '.table')

Sinnbeck's avatar

@aurorame I meant like

$data = new Data;
$data->setTable($db. '.table')->where('Name', $request->input('name'))

It is untested as I'm not near a computer

1 like
aurorame's avatar

@Sinnbeck i found 1 way in my solution, just set protected $table = $db . '.table'; in eloquent model, but it just select the database. Now i just need to create something like rules to all eloquent models like this (in order not to copy constantly in all models) and way to set the connection

UPD. find the way to set connection - $protected $connection = ... Now i need just the smth like rule to all other eloquent model to set right connection and db

Sinnbeck's avatar

@aurorame yeah setting connection is easy, but be sure to do it using the method. Otherwise you cannot change it when testing

public function getConnection()
 {
    return 'my_con';
} 
1 like
aurorame's avatar

@Sinnbeck how i can make smth like rules for all eloquent model to select correct connection and db`s?

Please or to participate in this conversation.