0

I'm using 2 databases in my Laravel application. I have an SQLite DB which is local and a remote MySQL DB. Right now I need to switch env files to connect to each DB when I need to. My question is, is it possible to switch env files so the models which I'm using for both of the DB work on the corresponding DB.

This project is fairly new so if anyone knows a better way to handle this I'm all ears.

Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63
Neavehni
  • 337
  • 1
  • 2
  • 14
  • 1
    Does this answer your question? [How to use multiple databases in Laravel](https://stackoverflow.com/questions/31847054/how-to-use-multiple-databases-in-laravel) – miken32 Nov 09 '20 at 16:29
  • No, I've already looked at this before creating a post. my question is how to use 1 model for 2 databases. – Neavehni Nov 09 '20 at 16:39

1 Answers1

1

You may define several connections on your config/database.php file and access each connection via the connection method on the DB facade:

$sqliteUsers = DB::connection('sqlite')->select(...);

$mysqlUsers = DB::connection('mysql')->select(...);

Check "Using Multiple Database Connections" Section on Laravel docs for more info.

You may use on method on eloquent models:

use App\User;

$sqliteUsers = User::on('sqlite')->get()

$mysqlUsers = User::on('mysql')->get();

You may also specify a connection for an eloquent model statically:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'sqlite';
}

Check "Database Connection" Section on Laravel docs for more info.

Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63