CodexBloom - Programming Q&A Platform

Laravel 10: Difficulty with Dynamic Database Connections Based on User Input

πŸ‘€ Views: 1 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
laravel database dynamic-connection PHP

This might be a silly question, but I'm trying to set up a multi-database connection in my Laravel 10 application where the database connection is determined at runtime based on user input. My goal is to switch the database connection dynamically depending on the user's selection from a dropdown menu. However, when I attempt to make a query using the selected connection, I'm encountering the following error: `SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES)`. I've made sure that the credentials I'm passing are correct, but it seems like Laravel is not applying the correct connection settings. Here’s the code snippet I’m using to set the connection dynamically: ```php public function switchDatabase(Request $request) { $dbConfig = $request->input('db_config'); // This should contain the necessary config details config(['database.connections.dynamic' => [ 'driver' => 'mysql', 'host' => $dbConfig['host'], 'port' => $dbConfig['port'], 'database' => $dbConfig['database'], 'username' => $dbConfig['username'], 'password' => $dbConfig['password'], 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ]]); DB::purge('dynamic'); // Clear the connection $users = DB::connection('dynamic')->table('users')->get(); // Attempting to query the users table return response()->json($users); } ``` I've also tried using `DB::purge()` before making the query, but the error persists. I want to ensure that the connection is not only set up correctly but also actually used for the query execution. Am I missing something in this setup? Is there a better way to manage dynamic database connections in Laravel? Any insights would be greatly appreciated! For context: I'm using Php on macOS. What am I doing wrong?