Reputation: 2564
What are the best practices to manage Laravel Migrations with more than one database?
Upvotes: 0
Views: 67
Reputation: 6269
In your app/config/database.php
Do this
return array(
'default' => 'mysql',
'connections' => array(
# Our primary database connection
'mysecond_database' => array(
'driver' => 'mysql',
'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Our secondary database connection
'myfirst_database' => array(
'driver' => 'mysql',
'host' => 'host2',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
then in your migrations you can do this
Schema::connection('mysecond_database')->create('users', function($table)
{
$table->increments('id'):
});
This will create the users
table in mysql2
connection(database)
to use another connection just change it like this
Schema::connection('myfirst_database')->create('posts', function($table)
{
$table->increments('id'):
});
if you want to retrieve data from one table
$users = DB::connection('mysecond_database')->select(...);
if you want to use eloquent you only need to define the connection in the model like so :
class users extends Eloquent {
protected $connection = 'mysecond_database';
}
Then you can do it easly like this
$users = User::all();
Upvotes: 1