TKoL
TKoL

Reputation: 13912

Laravel builder - specify a connection on the builder object

I have an eloquent query builder in Laravel

$builder = Model::orderBy('created_at', 'DESC');

I want to specify a connection to use, because I have a separate db for some data - let's call it 'archive' for example.

Now, I know I can do it statically, like $builder = Model::connection('archive'); [edit] ::on('archive'); apparently

But if I already have the $builder object, and can't use the static function, how can I do it on the builder object?

I've tried

$builder->connection('archive');
$builder->onConnection('archive');
$builder->setConnection('archive');

And these are all failing for me.

Upvotes: 0

Views: 63

Answers (1)

bluestar0505
bluestar0505

Reputation: 701

There are two solutions.

  1. Define in class
class MyModel extends Model {

    protected $connection= 'archive';

    protected $table = 'table_name';
}
  1. In a query
(new MyModel())->on('archive')->get();

Upvotes: 1

Related Questions