Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple database in Lumen

We've using Lumen for building API's , Now we need to access multiple databases.

Currently using .env for database config but unable to found the way to multiple databases in .env

where we need to read 2nd connection ...

like image 987
Govind Samrow Avatar asked Aug 17 '17 07:08

Govind Samrow


People also ask

Can we use two database in laravel?

By default, Laravel already provides several database connections such as sqlite, mysql, pgsql and sqlsrv. Because in this article we will try to create multiple database connections in laravel using mysql, so we need to add a mysql connection like the code above.


1 Answers

First, you'll need to configure your connections. If you don't already have one you'll need to create a config directory in your project and add the file config/database.php. It might look like this:

<?php

return [

   'default' => 'accounts',

   'connections' => [
        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST'),
            'port'      => env('DB_PORT'),
            'database'  => env('DB_DATABASE'),
            'username'  => env('DB_USERNAME'),
            'password'  => env('DB_PASSWORD'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
         ],

        'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB2_HOST'),
            'port'      => env('DB_PORT'),
            'database'  => env('DB2_DATABASE'),
            'username'  => env('DB2_USERNAME'),
            'password'  => env('DB2_PASSWORD'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
    ],
];

Once you've added your connection configurations, you can access them by getting the database manager object out of the container and calling ->connection('connection_name').

// Use default connection
app('db')->connection()->select('xx');
DB::connection()->select('yy');

// Use mysql2 connection
app('db')->connection('mysql2')->select('xx');
DB::connection('mysql2')->select('yy');

Hope this helps you!!

like image 121
Hiren Gohel Avatar answered Sep 20 '22 18:09

Hiren Gohel