Laravel 5.1 dynamic database connection

1.1k views Asked by At

I am using laravel5.1 with mongoDb. In my application i have separate database for each user.

When user login i set database as per user DB using Config::set('Key' : 'Value').

when i try to get current database connection using Config::get('database) everything worked fine but when i am trying to get data from database then it return default database data.

2

There are 2 answers

0
Gaurang Ghinaiya On BEST ANSWER

DB::purge('mongodb-name'); i used this after Config::set("Key","value"). And its work for me.

1
Armen Markossyan On

You have to override the connection property in the model as follows:

<?php

namespace App\Models;

class Model extends \Illuminate\Database\Eloquent\Model
{
    protected $connection = 'your_connection_name_from_database_config';
}

You can also set this value dynamically by calling $model->setConnection('mongo');

Hope this helps.