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

cevizmx's avatar
Level 17

Two different databases on same query

Hello everyone,

I learned a nice trick from one of our members here where you can use a connection like this when you have multiple databases used in Laravel.

DB::connection('conn_2')->select(...)

However, I came to a scenario where I need to use two connections on the same query. Something like this; SELECT * FROM conn_1.db.users JOIN conn_2.db.user_rights on ...

Is there any way I can use two connections on the same query? Maybe I can create two models and then try that way.

0 likes
2 replies
Vilfago's avatar
Vilfago
Best Answer
Level 20

Yes, you can specify the connection on each model, so you can create several model, and use eloquent relations to retrieve data from multiple databases.

nikulpaladiya's avatar

@minasmms you can try with this query

DB::table('database1.table1 as dt1')->join('database2.table2 as dt2', 'dt2.ID', '=', 'dt1.ID') ->select(['dt1.','dt2.'])->get();

Hope so, it will work

1 like

Please or to participate in this conversation.