Laravel Eloquent ORM error with multiple database connections

Ayb009

I'm trying to use the Laravel Eloquent ORM to interact with two different databases in my application. I have defined the two database connections in my config/database.php file like this:

'connections' => [

    'primary_db' => [
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'primary_db',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'secondary_db' => [
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'secondary_db',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

],

I can connect to both databases using the DB::connection() method, but when I try to use Eloquent to query the second database, I get an "undefined table" error. Here's an example of my code:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $connection = 'secondary_db';
    protected $table = 'users';
}

When I try to retrieve all users using the following code:$users = User::all(); I get this: Illuminate\Database\QueryException : SQLSTATE[42S02]: Base table or view not found: 1146 Table 'primary_db.users' doesn't exist (SQL: select * from users)

Ayb009

I found this : $users = User::on('secondary_db')->get(); It works. This on() method allows you to specify the name of the database connection to use for a particular query.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related