1 week ago

Automatically connect to different database from the form input for the AuthServiceProvider

Posted 1 week ago by surajitbasak109

Hi there,

I am trying to build an API using Lumen for my Point of Sale project. I have a login system where user can Select Unit(Database) name and after that the branch will be populated in another select field, then the user can enter their username and password to use the application.

I already got a solution which I don't think is a good idea. That is if there is a get parameter in the request(?dbname=xxxx) it will connect to that database.

Another solution I got from the internet, which is a good idea that is I can dynamically change the database connection name on runtime with the post request parameter or using method parameter.

But the problem is I am using "tymon/jwt-auth" library for the JWT Authentication, and I am thinking to find a logic to implement if I can somehow change the database name in runtime. Is it possible to do that?

In config/database.php file:

'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', ''),
            'port' => env('DB_PORT', '3306'),
            'database' => !empty($_GET['dbname']) ? $_GET['dbname'] : env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],

Please sign in or create an account to participate in this conversation.