Phil
Phil

Reputation: 2246

laravel how to use query builder DB::table(..) with DB::connection()

I have 2 databases defined in config/databases, mysql and mysql2
The default connection is mysql

I need to get this data from mysql2

$programs=DB::table('node')->where('type', 'Programs')->get();

The docs tell me I can change the connection using

$programs=DB::connection('mysql2')->select(...)

which would let me run a sql statement to get an array for $programs. But I am wondering if there is a way to combine the 2 statements i.e. use query builder on specific db::connection.

Upvotes: 12

Views: 37955

Answers (2)

rish2050
rish2050

Reputation: 11

The above answer should work for relational databases. In case you are not using relational database, but using Laravel and MongoDB, you can use below statements:

// Access the users document from the collection
$usersCollection1 = DB::connection('mongodb')->collection('collection1')->get();

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

You should use:

$programs=DB::connection('mysql2')->table('node')->where('type', 'Programs')->get();

Upvotes: 33

Related Questions