0

I have a Laravel project. I have three databases. the first database is for the current project and I can use migrations. I know how I can connect to it and use migrations. Two other databases I should connect to it. but I want to use Model instead of using the query. for example:

in the second database, I have this table:

works
id - title

in the third database, I have this table:

logics
id - title

I want to use Work::first() or Logic::get() in current my Laravel project;

What can I do?

Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • Would https://laravel.com/docs/10.x/eloquent#database-connections help? – brombeer Jul 12 '23 at 08:03
  • 1
    Why don't you use `protected $connection = 'DB_Connection';` in your model? https://stackoverflow.com/questions/31847054/how-to-use-multiple-databases-in-laravel/31847198#31847198 – Abdulla Nilam Jul 12 '23 at 08:10

2 Answers2

1

I assume you already have defined the 3 connections in config/database.php if so then in each model you need also to define

protected $connection = 'yourConnection';
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Imad
  • 11
  • 1
1

You can add new database connection in /config/database.php

For example (mysql connection):

'yourNewConnectionName' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('ADB_HOST', '127.0.0.1'),
            'port' => env('ADB_PORT', '3306'),
            'database' => env('ADB_DATABASE', 'forge'),
            'username' => env('ADB_USERNAME', 'forge'),
            'password' => env('ADB_PASSWORD', ''),
            'unix_socket' => env('ADB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => false,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

Then in each model you need to define:

protected $connection = 'yourNewConnectionName';
zahiruddin
  • 53
  • 7