File manager - Edit - /var/www/payraty/inventory_main/app/Console/Commands/MigrateAdminRolesPerOrg.php
Back
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use App\Models\User; use App\Models\RoleHasPermission; use Illuminate\Support\Facades\DB; class MigrateAdminRolesPerOrg extends Command { protected $signature = 'roles:migrate-admins-per-org'; protected $description = 'Clone global admin role per organisation and reassign users'; public function handle() { DB::beginTransaction(); try { $globalAdminRole = Role::where('id', 1)->firstOrFail(); // $permissionIds = DB::table('role_has_permissions') // ->where('role_id', 1) // ->pluck('permission_id') // ->toArray(); $adminUsers = User::where('user_type', 'admin') ->whereHas('roles', fn($q) => $q->where('id', 1)) ->get(); $orgsHandled = []; foreach ($adminUsers as $user) { $orgId = $user->organisation_id; if (!$orgId) { $this->warn("User ID {$user->id} does not have an organisation_id. Skipping..."); continue; } if (in_array($orgId, $orgsHandled)) { $this->warn("Multiple admins found for org {$orgId}. Cleaning up..."); $user->removeRole($globalAdminRole); continue; } $newRole = Role::firstOrCreate( [ 'name' => 'admin', 'guard_name' => 'web', 'organisation_id' => $orgId, ], [ 'is_admin' => true, 'created_by' => $user->id, ] ); RoleHasPermission::where("role_id", $newRole->id)->delete(); $permissionIds = DB::table('role_has_permissions') ->where('role_id', 1) ->pluck('permission_id') ->unique() ->map(fn($id) => (int) $id) ->filter() ->values() ->toArray(); $rows = []; foreach ($permissionIds as $permissionId) { $rows[] = [ 'role_id' => $newRole->id, 'permission_id' => $permissionId, ]; } DB::table('role_has_permissions')->where('role_id', $newRole->id)->delete(); try { DB::table('role_has_permissions')->insertOrIgnore($rows); $this->info("Inserted " . count($rows) . " permissions for role {$newRole->id}"); } catch (\Exception $e) { $this->error("Failed to insert permissions: " . $e->getMessage()); } app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions(); $user->removeRole($globalAdminRole); $user->assignRole($newRole); $orgsHandled[] = $orgId; $this->info("✅ Migrated user {$user->id} to new admin role for org {$orgId}"); } DB::commit(); $this->info('🎉 Migration complete.'); } catch (\Throwable $e) { DB::rollBack(); $this->error("❌ Error occurred: " . $e->getMessage()); } } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.30 | Generation time: 0 |
proxy
|
phpinfo
|
Settings