Carol.Kar
Carol.Kar

Reputation: 5355

Laravel 8 - Changing database connection for model

I am using laravel 8 and would like to query a model from my production database.

I tried the following:

DB::connection('mysql_prod')->Company::where('symbol', $symbol)
            ->first();

However, I get the following error:

Undefined property: Illuminate\Database\MySqlConnection::$Company

I would like to get a laravel model - in this case Company - back.

Any suggestions how to implement this?

Upvotes: 0

Views: 570

Answers (2)

John Lobo
John Lobo

Reputation: 15319

use on if you are changing for one query.

 Company::on('mysql_prod')->where('symbol', $symbol)->first();

define $connection property in Company model so no need to mention connection

protected $connection = 'mysql_prod';

so query is

Company::where('symbol', $symbol)->first();

Ref:https://laravel.com/docs/8.x/eloquent#database-connections

Upvotes: 2

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

You can use

Company::on('mysql_prod')->where('symbol', $symbol)
            ->first();

Upvotes: 1

Related Questions