DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Nguyแป…n Thanh Hรฒa
Nguyแป…n Thanh Hรฒa

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

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'),
],

when you edit success, you can using it

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

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

DB::connection('mysql2')->select(...)->(...);

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

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

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;
    }

Post:Connecting Multiple Databases in Laravel 5.8

Top comments (0)

๐ŸŒš Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.