Dan
Dan

Reputation: 6583

Set database for model?

I'm working on a Laravel 4 based site which works over multiple databases. There is one query I need to run on each request that pulls a record from a different database.

Is there a way I can somehow tie this particular model to the other database so I can just retrieve it as usual?

$client = Client::find(Session::get('client_id'));

Any advice appreciated.

Thanks

Upvotes: 12

Views: 14788

Answers (1)

Andreyco
Andreyco

Reputation: 22872

// Model
class Client extends Eloquent
{
    protected $connection = 'masterDb';
}


// config/database.php
'masterDb' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'name',
    'username'  => 'user',
    'password'  => 'pass',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

You can create as many named connections as you wish. Set one of them as default, each model can use any of these connections later.

Upvotes: 30

Related Questions