Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3 DB Select with different database

Tags:

sql

laravel-5

I have 3 databases defined in my app (legacy not my design!) and I want to use DB Select to run a raw SQL but not from the primary DB.

What is the syntax for telling

 DB::select('SELECT....

to use a particular predefined connection?

like image 989
Jim Avatar asked Feb 16 '26 15:02

Jim


1 Answers

The reason why the $connection declaration seems to be ignored is simple: with the Query Builder (DB class) you are actually not using the Eloquent ORM. If you want to use the Query Builder, you have to manually declare the connection if different from default, like this...

DB::connection('connection-name')

Remember that the Eloquent models are extensions of the Query Builder. For taking advance of the Eloquent model (and in your case of the $connection protected property) import the Eloquent Model with a use statement

use App\YourModel;

and build the query with the same methods that you'd use with the query builder.

Useful links to Laravel docs:

Eloquent (check the "Database connection" section) / Database - Multiple database connections

like image 163
Andrea Alhena Avatar answered Feb 19 '26 04:02

Andrea Alhena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!