Home » Php » php – laravel how to use query builder DB::table(..) with DB::connection()

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

You should use:

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