1

I'm trying to separate my tables into different schemas while writing migration files with Laravel.

I was wondering what's the best approach to do it. Currently, the table creation goes like:

 Schema::create('schema_name.table_name', function (Blueprint $table) {
        $table->increments('id');
        (...)
    });

Should I try to use a different connection, another option or it's ok like this?

2
  • Don't you google it first before posting question? Commented Sep 21, 2017 at 5:50
  • yes I did. and I actually know how to do it. But I don't like this approach. Do you have any contribution besides googling? Commented Sep 21, 2017 at 11:19

1 Answer 1

6

try this

first in config/database.php add another connection

'connections' => [
    'mysql' => [...],

    'mysql1' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_NAME', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

      ...
]

Then in migration

Schema::connection('mysql1')->create('table_name', function (Blueprint $table) {
    $table->increments('id');
    (...)
});
Sign up to request clarification or add additional context in comments.

3 Comments

I added a connection with other schema set. In the Migration class extended by laravel migrations there's a $connection property. It doesn's seems to change anything if I set my connection there. Do you know how does it works?
in this answer i added mysql1 new connection then i changed connection in migration as above then simply run php artisan migrate it will migrate. after that in Model add protected $connection = 'mysql1' and use model as you always do.
I wish there was a better way... anyway, I think that's the proper answer

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.