skip to Main Content

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?

2

Answers


  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';
    
    Login or Signup to reply.
  2. 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';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search