Jim Jim - 1 year ago 307
SQL Question

Laravel 5.3 DB Select with different database

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


to use a particular predefined connection?

Answer Source

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...


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download