Connecting Multiple Databases in Laravel 5.8

Kết nối nhiều databases trong Laravel 5.8, Thông thương ta có nhiều dự án, trong các dự án đó ta cũng connect nhiều cở sở dữ liệu khác nhau, để làm được điều đó, ta cần chỉnh lại file trong Laravel như sau:

File .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret

DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret


Trong file config/database.php ta chỉnh lại các thông tin kết nối:

'mysql' => [
    'driver'    => env('DB_CONNECTION'),
    'host'      => env('DB_HOST'),
    'port'      => env('DB_PORT'),
    'database'  => env('DB_DATABASE'),
    'username'  => env('DB_USERNAME'),
    'password'  => env('DB_PASSWORD'),
],

'mysql2' => [
    'driver'    => env('DB_CONNECTION_SECOND'),
    'host'      => env('DB_HOST_SECOND'),
    'port'      => env('DB_PORT_SECOND'),
    'database'  => env('DB_DATABASE_SECOND'),
    'username'  => env('DB_USERNAME_SECOND'),
    'password'  => env('DB_PASSWORD_SECOND'),
],

Sau khi ta chỉnh các file connection xong, điều ta cần quan tâm là, làm thế nào để dùng database.

//Shema
Schema::connection('mysql2')->create('posts', function($table)
{
           $table->bigIncrements('id');
            $table->string('title');
            $table->string('keyword');
            $table->string('des');
            $table->string('slug');
            $table->string('image');
            $table->string('content');
            $table->timestamps();
});

Trong đoạn shema bên trên ta chỉ tới database ta cần dùng, sao đó ta có thể chạy cậu lệnh migration như sau:
php artisan migrate --database=mysql2

Đối với Query Builder ta có thể dùng kết nối trực tiếp như thế này:
DB::connection('mysql2')->select(...)->(...);

Còn cài đặt trong Eloquent để nhận connection đến database, ta cần thêm $connection khai báo trong Model:

class Post extends Model
{
     protected $connection = 'mysql2';
}

Trong PostController.php ta có thể set connection đến database như sau:

user App\Post;
public function getAllPost()
    {
        $post = new Post;
        $post->setConnection('mysql2');
        $data = $post->find(1);
        return $data;
    }

Chúc các bạn thành công!

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)