This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

Tschallacka
Tschallacka

I'd like to make multiple database connections in OctoberCMS and be able to define in a plugin settings which database connection i'd like to use. So the plugin will use the database defined in the setting.

Is there a native way to select an active connection from connections to use in a plugin? I need it to communicate with a central product database that we do not wish to import into the CMS website.

Keios
Keios

Sure you can, you can define db connection even in runtime using config repository like this:

Config::set('database.connections.' . $yourConnectionName, $yourConnectionParametersArray);

Also, last time I checked you could define connection name in model class (https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L40) and this worked pretty well, at least in 4.2, you could probably go even more dynamic, make a setConnection method and operate on multiple connections with same model, but this isn't the best idea imho.

Tschallacka
Tschallacka

Thanks! but I went with a different approach with the help of the laravel docs

In config/database.php duplicate the sql connection entry in the array rename for proper database/login, give it fancy name for example connection name then in the Models declare

public $connection = 'connectionname'; 

and in the schema creator use

 Schema::connection('connectionname')-> 

instead of

 Schema:: 

thats it basically :-) The things you do in your models/controllers will now be written to the other database.

ichakesachin3010215
ichakesachin3010215

Hi, I have followed same approach like what Tschallacka has done. But i m facing problem when validating form fields,

Look at following snippet:

class User extends UserBase
{
    public $connection = 'plugindb'; 
    /**
     * @var string The database table used by the model.
     */
    protected $table = 'users';

    /**
     * Validation rules
     */
    public $rules = [
        'name' => 'required',
        'surname' => 'required',
        'email' => 'required|between:3,64|email|unique:db_plugin.users',
        'mobile' => 'numeric',
        'password' => 'required:create|between:6,16|confirmed',
        'password_confirmation' => 'required_with:password|between:6,16',        
    ];

To validate email as unique, i need to use "db_plugin" database name as suffix with table otherwise it throws "Exception". But I want to do it dynamic like database name will be available depend on connection using. If I removed database name then it takes default database which application using.

Please suggest best approach to implement it in correct way?

Last updated

1-4 of 4

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.