How to connect Dynamic database in Laravel

Avatar
C

Callum Davies

Senior Backend Engineer••
8132Views
5mRead
0Reactions

Hello,In this tutorial, i am showing you, how to manage multiple database connection in one laravel project. Sometimes, we need to multiple database for one project. Get ready for move...

Step 1:

Create a new laravel using below command

composer create-project laravel/laravel demo --prefer-dist

Step 2:

As we manage multiple database connection dynamically, i am adding database name into the users table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddDbNameInUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('database_name');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('database_name');
        });
    }
}

Step 3:

Update User Model

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'db_name',
    ];
}

Step 4:

Add route into web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;

Route::get('user', [TestController::class, 'user'])->name('user');

Step 5:

Controller code

<?php
  
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Config;
use Hash;
use DB;

class TestController extends Controller
{
    public function user(Request $request)
    {
        $name = $request->name;
        $user = User::create([
            'name' => $name,
            'email' => $name.'@gmail.com',
            'password' => Hash::make('12345678'),
            'database_name' => $name,
        ]);
        
        $preDatabase = Config::get('database.connections.mysql.database');
        DB::statement("CREATE DATABASE IF NOT EXISTS $name");

        $new = Config::set('database.connections.mysql.database', $user->database_name);
        DB::purge('mysql');
        DB::reconnect('mysql');
        \Artisan::call('migrate');

        Config::set('database.connections.mysql.database', $preDatabase);
        return dd('create database and user data');
    }
}

Finally, we are done for configuring multiple database connection. Open any browser and serve the application. When youhttp://localhost:8000/user?name=first_database

Hope, it wil help you.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles