27

I want to connect to another database sometimes.

I created a config.php with the database connection data.

But how can i tell laravel to connect to this database insted of using the config/database.php?

For example when using the Schema class.

Since no one seems to understand what i want.

I DON'T want to use the config/database.php, i want to use a different config file on a different location.

11
  • Since you're not giving any specific code to "port", take a look here in case it answers your question. Jul 1, 2013 at 17:18
  • What code? As i said i want to create a additional config.php with the database settings and connect to this. The question is how can i tell laravel to use this config insted of the config/database.php.
    – TheNiceGuy
    Jul 1, 2013 at 17:20
  • The linked page shows how to add multiple database configs to database.php, and how to select which one to use to connect to/query. Jul 1, 2013 at 17:22
  • I appreciate that you try to help me but i wrote it 2 times now. I DON'T want to use the config/database.php. I want to create an additional config.php file at a different location.
    – TheNiceGuy
    Jul 1, 2013 at 17:23
  • 1
    Then you'd just use Schema::connection('foo')->create('users', function($table)... to use the 'foo' database. Jul 1, 2013 at 17:34

6 Answers 6

60

It sounds like you figured this out. Here's how I'd accomplish it anyway for other people coming in, or in case something useful is here for you.

First, Add a second connection in app/config/database.php. Note: That file path may change depending on your environment.

<?php
return array(
    'connections' => array(
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

Second, in your code, you can use (as mentioned) the 2nd connection where you would like:

Schema::connection('mysql2')->create('users', function($table) {})

There's more documentation on this - see Accessing Connections.

Eloquent ORM You can define the variable for "connection" in an eloquent class to set which connection is used. That's noted in the Basic Usage section.

See that variable on here on Github and the method which you can set to set the connection dynamically here.

Edit The OP has made it clear that they do not wish to use the config/database.php file for config.

However without explaining further, I can't comment. I'm happy to help - sounds like it would be useful to know why the config/database.php file can't/shouldn't be used, as this can help us ascertain the problem and create a useful solution.

3
  • 1
    I use a ModulSystem. Tha'ts the reason ;)
    – TheNiceGuy
    Jul 2, 2013 at 10:31
  • What about validation? For example the "exists" validation rule. How do you tell it to use some other connection/database?
    – cen
    Apr 5, 2014 at 14:38
  • You can over-ride what connection it set in the Validation service provider. I don't know about if you need to switch between database connections. You'll have to dig into the code and do some extending/over-riding.
    – fideloper
    Apr 5, 2014 at 15:44
12

I believe you want to implement some kind of logical sharding where databases would be dynamically created.

In such scenario in laravel you can dynamically add a database config, like below

$conn = array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'DATABASE',
    'username'  => 'USERNAME',
    'password'  => 'SOME_PASSWORD',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
);

Config::set('database.connections.DB_CONFIG_NAME', $conn);

Now to connect via eloquent

MODEL::on('DB_CONFIG_NAME')->WHAT_EVER('1');

Incase of Query Builder you can do

$DB = DB::connection('DB_CONFIG_NAME');

use $DB->select() for querying now.

Hope this would help devs looking for a possible solution for this question

2
  • This doesn't seem to work with Laravel 5.2, DatabaseManager.php:239 throws exception 'Database [database.connections.DB_CONFIG_NAME] not configured.' I also tried App::make('config')->set('database.connections.DB_CONFIG_NAME', $conn), with the same result. Any idea? Feb 23, 2016 at 23:14
  • Sorry, my mistake. I missed the simple fact that you don't need the database.connections. prefix when referencing the configured connection later. For some reason that error message completely threw me off. Feb 24, 2016 at 17:00
11

Remember that Laravel 4 is actually a collection of components, and you can use these components solo.

https://github.com/illuminate/database

There is an example here that shows off how interacting with the Capsule class works:

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => 'password',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
]);

// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Set the cache manager instance used by connections... (optional)
$capsule->setCacheManager(...);

// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();

This is a bunch of bootstrapping that you'll need to run, so tuck it away somewhere in a function or method.

But, its absolutely possible.

0
5

There is a simpler solution. If you are using Larave 4 there is an option that worked for me. Recently they added $table variable that you can specify in your model. Refer to this link.

class User extends Eloquent {

    protected $table = 'my_users';

}

If you are using MySQL, you can do the following:

class User extends Eloquent {

    protected $table = 'mydbname.my_users';

}

If you are using SQL Server, you can do this:

class User extends Eloquent {

    protected $table = 'mydatabase..my_users';

}

My Config file had DB1 specified but I created a model which wants to access DB2 in the same MySQL host. So this was a quick and dirty way to accomplish this.

Now I don't fully leverage Eloquent ORM all the time so this "hack" may not work with Many to Many or one to Many Eloquent methods.

One another idea I had but I didn't actually try was creating a stored procedure (routine) in DB1 and inside of that routine I can access DB2 tables by querying link this:

SELECT * from db2.mytable where id = 1;
1
  • 1
    If you are happy with having/able to have the same user access both databases, this is a beautifully elegant solution.
    – voidstate
    Oct 23, 2015 at 9:00
3

To use a config file in another location, say src/config:

use Config;


$this->dbConfig = Config::get('appname::dbInfo.connections.test');
$this->database = $this->dbConfig['database'];
$this->username= $this->dbConfig['username'];
$this->password= $this->dbConfig['password'];

Where dbInfo is a simple php file in your app's src/config directory returning an array containing the element connections which is an array of database properties.

You can tell Laravel to use an external config file using:

Config::set("database.connections.test", $this->dbConfig);
DB::connection("test");
1

Edit bootstrap/start.php file and add your machine name (open terminal: hostname).

Add your machine to $env,

$env = $app->detectEnvironment(array(
    'mymachine' => array('mymachine.local'),
));
  1. Create a new path at 'app/config/mymachine'
  2. Add a copy of database.php with new config params.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.