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.

TheNiceGuy
  • 3,462
  • 8
  • 34
  • 64
  • Since you're not giving any specific code to "port", take a look [here](http://forums.laravel.io/viewtopic.php?pid=6387) in case it answers your question. – Joachim Isaksson Jul 01 '13 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 01 '13 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. – Joachim Isaksson Jul 01 '13 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 01 '13 at 17:23
  • Well.. Even if i would use the config/database.php. How can i use the Schema class with the other database then? DB:connection is not what i want to use. I need the Schema class. Seems like this is not possible? – TheNiceGuy Jul 01 '13 at 17:31
  • 1
    Then you'd just use `Schema::connection('foo')->create('users', function($table)...` to use the 'foo' database. – Joachim Isaksson Jul 01 '13 at 17:34
  • Okay thanks that works. Dunno why there is no info about that. But there is no way to use another config? – TheNiceGuy Jul 01 '13 at 17:42
  • Since i use a modul system that is not what i want. I need to specify the config at the needed point ;/. Not sure why you deleted your last comment :P – TheNiceGuy Jul 01 '13 at 17:43
  • Not to my knowledge then, but I've never mucked around in the code to see if it's possible. Maybe someone else here knows. – Joachim Isaksson Jul 01 '13 at 17:44
  • Okay. Hopefully anyone has an idea. Thank you anyways :) – TheNiceGuy Jul 01 '13 at 17:46
  • Deleted my comment since you need to include it in a specific way to make it work so was looking in the docs to get it right, was a bit simple to just say "include it" :) If it's not an option, I'll check it out later. – Joachim Isaksson Jul 01 '13 at 17:51

6 Answers6

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.

fideloper
  • 12,213
  • 1
  • 41
  • 38
  • 1
    I use a ModulSystem. Tha'ts the reason ;) – TheNiceGuy Jul 02 '13 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 05 '14 at 14:38
  • You can over-ride what connection it set in the [Validation service provider](https://github.com/laravel/framework/blob/4.1/src/Illuminate/Validation/ValidationServiceProvider.php#L30). 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 05 '14 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

Sudesh
  • 1,129
  • 3
  • 14
  • 29
  • 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? – Josip Rodin Feb 23 '16 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. – Josip Rodin Feb 24 '16 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.

Phil Sturgeon
  • 30,637
  • 12
  • 78
  • 117
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;
na-98
  • 909
  • 8
  • 16
  • 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 '15 at 09: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");
Janyk
  • 571
  • 3
  • 18
sturrockad
  • 4,460
  • 2
  • 19
  • 19
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.
Eduardo Stuart
  • 2,869
  • 18
  • 22