mercredi 13 juillet 2016

How to manage multiple databases in laravel with the same models?

I have an application that I have several instances of running on different servers. I'm now creating an admin application to connect to these applications to create and edit data such as the Users table.

When an admin logs in to the admin panel they can select a database to connect to which will bring them to a page where they can select the operation they want to perform on that database.

At the moment I'm setting a session variable to store the selected database and then overriding the Model constructor to set the $connection variable within each Model.

/**
 * The connection name for the model.
 *
 * @var string
 */
protected $connection;

/**
 * Create a new Eloquent model instance.
 *
 * @param  array  $attributes
 * @return void
 */
public function __construct(array $attributes = [])
{
    if(session('connection')){
        $this->setConnection(session('connection'));
    }

    parent::__construct($attributes);
}

This solution works fine for most tables and models but for the users table I run into the issue of needing to access the local admin users data and interact with a remote users model which means I need a different connection for each operation.

The only solution I can think of is to set a second session variable called isExternalOperation and set it to true when ever I need to access another database but this leads to alot of repeated code. e.g.

session('isExternalOperation' => true]);
// Create new User or something else
session('isExternalOperation' => false]);

My model constructor would then look like this:

/**
 * Create a new Eloquent model instance.
 *
 * @param  array  $attributes
 * @return void
 */
public function __construct(array $attributes = [])
{
    if(session('connection') && session('isExternalOperation')){
        $this->setConnection(session('connection'));
    }

    parent::__construct($attributes);
}

Is there any better way to handle this as this seems to be a bad way to go about it?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire