Neavehni
Neavehni

Reputation: 407

Laravel - Specify database connection on the fly

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.

Upvotes: 0

Views: 538

Answers (1)

Hafez Divandari
Hafez Divandari

Reputation: 9029

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.

Upvotes: 1

Related Questions