refactor: Simplify user migration command by removing unnecessary variable assignments and streamlining role assignment logic.
This commit is contained in:
parent
8e68c0b225
commit
99e326ad51
@ -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!');
|
||||
|
||||
Loading…
Reference in New Issue
Block a user