skip to Main Content

I have a initial page which has a drop down of 5 options, The 5 options are 5 different databases, The functionality that I need to achieve is the same for all databases.
The thing I want to do if I select Option A, it should connect to Database A and give me results on View A.
If I select Option B, it should connect to Database B and still give me results on View A.

I don’t want to make multiple views for the same thing.
Is there any way the above functionality could be achieved?

Thanks

3

Answers


  1. do you have multiple connections for different database in config/database.php?. If not, you could create multiple connections as database_a and database_b. If you already have multiple connections for different database, you could make different connection depending on the requests you get.

    use IlluminateSupportFacadesDB;`
    $users = DB::connection('yourdatabase')->select(/* ... */);
    

    link : https://laravel.com/docs/11.x/database section #Using Multiple Database Connections

    Hope it helps you! Tell me if it’s not working.

    Login or Signup to reply.
  2. You could just change your database query’s connection depending on the value sent as the selected option

    <select name="database_id">
        <option value="A">Database A</option>
        <option value="B">Database B</option>
        <option value="C">Database C</option>
        ...
    </select>
    
    public function your_endpoint_here(Request $request)
    {
        $map = [
            'A' => ['db' => 'db_a', 'view' => 'view_a'],
            'B' => ['db' => 'db_b', 'view' => 'view_b'],
            'C' => ['db' => 'db_c', 'view' => 'view_c'],
            ...
        ];
    
        $data = DB::connection($map[$request->database_id]['db'])
            ->from($map[$request->database_id]['view'])
            ...
            ->get();
    
        // return $data as json or return view with $data
    }
    

    Or alternatively your db connection could be part or the url.

    Login or Signup to reply.
  3. If you only need to use one database at a time, you can simply modify the basic MySQL connection, but you can also declare new connections as needed in the config/database.php file.

    return [
      'connections' => [
        'mysql' => [
          'driver' => 'mysql',
          'url' => env('DATABASE_URL'),
          'host' => env('DB_HOST', '127.0.0.1'),
          'port' => env('DB_PORT', '3306'),
          'database' => env('DB_DATABASE', 'forge'),
          'username' => env('DB_USERNAME', 'forge'),
          'password' => env('DB_PASSWORD', ''),
          // ...
        ],
        'another_name' => [
          'driver' => 'mysql',
          'url' => env('DATABASE_URL'),
          'host' => env('DB_HOST', '127.0.0.1'),
          'port' => env('DB_PORT', '3306'),
          'database' => env('DB_DATABASE', 'forge'),
          'username' => env('DB_USERNAME', 'forge'),
          'password' => env('DB_PASSWORD', ''),
          // ...
        ],
      ],
    ];
    

    Let’s assume that the database selection occurs at the /login URL, and the database usage takes place on all routes starting with /admin. You can declare a middleware that will be associated with every route starting with /admin, and for such a route, it will set the name of the selected database.

    At the /login URL, you can save the name of the selected database into a session variable. Afterward, you redirect the user to an /admin/tables or some kind of homepage, where the middleware is triggered. The middleware then utilizes the session variable, retrieves the requested database name, and sets it in the connection as follows.

    /* app/Http/Middlewares/DatabaseSelector.php */
    
    namespace AppHttpMiddleware;
    
    use Closure;
    use IlluminateHttpRequest;
    use IlluminateSupportFacadesConfig;
    use IlluminateSupportFacadesDB;
    
    class DatabaseSelector
    {
      public function handle(Request $request, Closure $next)
      {
        if (! $request->session()->exists('selectedDatabase')) {
           return redirect()->to('login');
        }
    
        $databaseName = $request->session()->get('selectedDatabase');
    
        if (config('database.connections.another_name.database') !== $databaseName) {
          DB::disconnect('another_name');
          Config::set('database.connections.another_name.database', $databaseName);
          DB::reconnect('another_name');
        }
    
        return $next($request);
      }
    }
    
    /* app/Http/Kernel.php */
    
    protected $routeMiddleware = [
      // Other middleware declarations...
      'DatabaseSelector' => AppHttpMiddlewareDatabaseSelector::class,
    ];
    
    /* routes/web.php */
    
    Route::prefix('admin')->middleware('DatabaseSelector')->group(function () {
      // Define routes under /admin here
      Route::get('/', function () {
        // Your route logic here
      });
    
      // Add more routes as needed
    });
    

    So, on every /admin route where the DatabaseSelector runs, you can use DB::connection('another_name') for querying. You can associate Eloquent Models with it by setting the $connection value to another_name in the Model file, etc.

    The connection named another_name will always connect to the database with the selected name. On the /login page, its only job is to precisely write the name of the database to the selectedDatabase session variable, selecting one from the 5 databases available.

    /* routes/web.php */
    
    Route::get('/login', 'DatabaseController@showSelectDatabase')->name('login');
    Route::post('/login', 'DatabaseController@selectDatabase');
    
    /* app/Http/Controllers/DatabaseController.php */
    
    use IlluminateHttpRequest;
    use IlluminateSupportFacadesSession;
    
    class DatabaseController extends Controller
    {
      public function showSelectDatabase()
      {
        $databases = ['database1', 'database2', 'database3', 'database4', 'database5'];
    
        return view('login', ['databases' => $databases]);
      }
    
      public function selectDatabase(Request $request)
      {
        $selectedDatabase = $request->input('selectedDatabase');
        
        Session::put('selectedDatabase', $selectedDatabase);
    
        return redirect('/admin');
      }
    }
    
    <!-- login blade -->
    
    <ul>
      @foreach($databases as $database)
        <li>
          <!-- this Route::post calls the login and passes it the hidden input field, there is one separate form for each of your databases -->
          <form method="post" action="{{ route('login') }}">
            @csrf
            <input type="hidden" name="selectedDatabase" value="{{ $database }}">
            <button type="submit">{{ $database }}</button>
          </form>
        </li>
      @endforeach
    </ul>
    

    Of course, I tried to demonstrate the logic. Try to interpret and consider what logic you would need. The key is that you can declare connections, and you can modify their data at runtime based on the description. I provided you with an example where you can select the database at the /login URL, and the middleware invoked at the /admin URL automatically checks and sets it in the config.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search