"how to use multiple database in lumen" Code Answer

5

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!!

By Eric Brown - Cal on January 11 2022

Answers related to “how to use multiple database in lumen”

Only authorized users can answer the Search term. Please sign in first, or register a free account.