DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

Connecting Multiple Databases in Laravel 5.8

You need config 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
Enter fullscreen mode Exit fullscreen mode

Continue, open file config/database.php in folder config, add lists connection

'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'),
],
Enter fullscreen mode Exit fullscreen mode

when you edit success, you can using it

//shema in migration database
Schema::connection('mysql2')->create('some_table', function($table)
{
$table->increments('id'):
});
Enter fullscreen mode Exit fullscreen mode

You can also define custom connection with query builder as shown below

DB::connection('mysql2')->select(...)->(...);
Enter fullscreen mode Exit fullscreen mode

Using connection Model in Laravel Eloquent, you can add $connection to Model

class Post extends Model
{
     protected $connection = 'mysql2';
}
Enter fullscreen mode Exit fullscreen mode

In file PostController.php, you set connnection to database need using

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

Post:Connecting Multiple Databases in Laravel 5.8

Top comments (0)