From 99e326ad51da0d9cc1678450a02e10d002efd2f4 Mon Sep 17 00:00:00 2001 From: Yoga Pangestu Date: Mon, 16 Mar 2026 13:45:48 +0700 Subject: [PATCH] refactor: Simplify user migration command by removing unnecessary variable assignments and streamlining role assignment logic. --- app/Console/Commands/MigrateUserCommand.php | 27 +++++++++------------ 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/app/Console/Commands/MigrateUserCommand.php b/app/Console/Commands/MigrateUserCommand.php index aa2d4ca..859ae9b 100644 --- a/app/Console/Commands/MigrateUserCommand.php +++ b/app/Console/Commands/MigrateUserCommand.php @@ -7,7 +7,6 @@ use App\Models\User; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; class MigrateUserCommand extends Command @@ -33,8 +32,7 @@ public function handle() { $this->info('Starting user migration...'); - $legacyConn = DB::connection('mysql_second'); - $legacyUsers = $legacyConn->table('users')->get(); + $legacyUsers = DB::connection('mysql_second')->table('users')->get(); if ($legacyUsers->isEmpty()) { $this->warn('No users found in legacy database.'); @@ -42,36 +40,35 @@ public function handle() return; } - $this->withProgressBar($legacyUsers, function ($legacy) { - // Skip if user already exists with same email, but ensure role is synced if needed + foreach ($legacyUsers as $legacy) { $user = User::where('email', $legacy->email)->first(); + $roleName = $this->mapRole($legacy->role); if (! $user) { + $username = $this->generateUniqueUsername($legacy->name, $legacy->email); - // Using DB facade directly to insert ensures the legacy password hash - // is NOT double-hashed by the model's "hashed" cast. $userId = DB::table('users')->insertGetId([ 'id' => $legacy->id, 'name' => Str::limit($legacy->name, 100), 'email' => $legacy->email, 'username' => $username, - 'password' => $legacy->password, // Preserving legacy hash - 'is_active' => $legacy->status == '1' ? IsActive::ACTIVE->value : IsActive::INACTIVE->value, + 'password' => $legacy->password, + 'is_active' => $legacy->status == '1' + ? IsActive::ACTIVE->value + : IsActive::INACTIVE->value, 'email_verified_at' => now(), 'created_at' => $legacy->created_at ?? now(), 'updated_at' => $legacy->updated_at ?? now(), ]); $user = User::find($userId); - } - // Map and Assign Role - $roleName = $this->mapRole($legacy->role); - if ($roleName && $user) { - $user->syncRoles([$roleName]); + if ($roleName) { + $user->syncRoles([$roleName]); + } } - }); + } $this->newLine(); $this->info('User migration completed successfully!');