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 you http://localhost:8000/user?name=first_database
Hope, it wil help you.
Subscribe to the Email Newsletter