1

I have a Model for DB tables, basically is one table but in different databases, How can I set a connection to DB in Model?

protected $connection = 'ls';

Above code is not that I am looking for, I need to pass host, port, username and password. because conection are stored in DB not in config file. I was thinking for function __construct() and call like Model($data)::where()..etc

Or I am thinking wrong way, can somebody give me an better idea.?

1 Answer 1

2

You can connect from Eloquent model by maintaining following aspects

First you can define multiple connection in database.php file

<?php
return array(

'default' => 'mysql',

'connections' => array(

    # Our primary database connection
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'host1',
        'database'  => 'database1',
        'username'  => 'user1',
        'password'  => 'pass1'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

    # Our secondary database connection
    'mysql2' => array(
        'driver'    => 'mysql',
        'host'      => 'host2',
        'database'  => 'database2',
        'username'  => 'user2',
        'password'  => 'pass2'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
),
);

You have your default connection still set to mysql . This means that, unless we specify otherwise, the application will use that mysql connection.

Now in your model you can specify which connection to use

<?php

class SomeModel extends Eloquent {

protected $connection = 'mysql2';

 }

You can also define the connection at runtime via the setConnection method.

 <?php

 class SomeController extends BaseController {

 public function someMethod()
 {
    $someModel = new SomeModel;

    $someModel->setConnection('mysql2');

    $something = $someModel->find(1);

    return $something;
}

}
Sign up to request clarification or add additional context in comments.

1 Comment

As I mentioned in my question, I am looking for something else, the connection are stored in DB not in config file, And I need to pass the connection parameter like (host, username, pass) to a model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.