0

Laravel uses config/database.php to define DB connections,

I have other database connections, and I would like to store those connections in config/other.php

And after use it in a model or via function
$model->setConnection(config('other.fisrt_connection'))

But I failed doing so.

It is possible to set connection from another config file in laravel 5.1?

And also when DB connection is setted how pass this connection to relationship models?

4
  • Why do you want it in a different file? Commented Nov 17, 2015 at 22:40
  • Check this. Commented Nov 17, 2015 at 22:41
  • @JosephSilber I know it is strane, but I need to put some data to each connection, like description and etc. Commented Nov 17, 2015 at 22:58
  • @TheAlpha hmm didnt get it is still uses config/database.php Commented Nov 17, 2015 at 22:59

2 Answers 2

1

Multiple Database Connection

If your application needs to interact with multiple DB you can define all the required DB details in app/config/database.php file. Adding another config file is not recommended.

     'connections' => array(
             'mysql1' => array(         // mysql1 -> connection_name
               'driver'    => 'mysql',
               'host'      => 'localhost',
               'database'  => 'example',
               'username'  => 'example',
               'password'  => 'example',
               ..
           ),
             'mysql2' => array(         // mysql2 -> connection_name
               'driver'    => 'mysql',
               'host'      => 'localhost',
               'database'  => 'example2',
               'username'  => 'example2',
               'password'  => 'example2',
               ..
          ),
       ),

When writing queries you can connect to the required DB likewise:

If Query Builder

$users = DB::connection('connection_name')->select(...);

Eloquent

Within the model:

class User extends Eloquent {    
    protected $connection = 'connection_name';    
}

When trying to fetch values use as follows

$userModel = new User();
$userModel->setConnection('connection_name');
$result = $userModel->newQuery()->find(1);

Laravel doc

Hope this would get you started.

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

Comments

0

Please write all of the DB connection settings to database.php. Because all DB method reference this file.

It is also possible to selectively use multiple DB connections. For more information please reference manual page.

http://laravel.com/docs/5.1/database#accessing-connections

But, if you want to use the absolutely other files, will need to make a few modifications to the Code of Laravel. Not recommended.

Comments

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.