RefreshPermissions.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Commands;
  3. use App\Enums\UserTypeEnum;
  4. use App\Models\Permission;
  5. use App\Models\UserTypePermission;
  6. use Illuminate\Console\Command;
  7. use Database\Seeders\PermissionSeeder;
  8. use Database\Seeders\UserTypePermissionSeeder;
  9. use Illuminate\Support\Facades\Cache;
  10. class RefreshPermissions extends Command
  11. {
  12. public function __construct(
  13. protected PermissionSeeder $permissionSeeder,
  14. protected UserTypePermissionSeeder $userTypePermissionSeeder,
  15. ) {
  16. parent::__construct();
  17. }
  18. /**
  19. * The name and signature of the console command.
  20. *
  21. * @var string
  22. */
  23. protected $signature = 'permissions:refresh';
  24. /**
  25. * The console command description.
  26. *
  27. * @var string
  28. */
  29. protected $description = 'Refresh all permissions and user type permissions';
  30. /**
  31. * Execute the console command.
  32. *
  33. * @return int
  34. */
  35. public function handle()
  36. {
  37. $this->info('Starting permissions refresh...');
  38. try {
  39. // Run the Permission seeder
  40. $this->info('Running Permission seeder...');
  41. Permission::truncate();
  42. $this->permissionSeeder->run();
  43. $this->info('Permission seeder completed successfully.');
  44. // Run the UserTypePermission seeder
  45. $this->info('Running UserTypePermission seeder...');
  46. UserTypePermission::truncate();
  47. $this->userTypePermissionSeeder->run();
  48. $this->info('UserTypePermission seeder completed successfully.');
  49. // Clear cache
  50. foreach (UserTypeEnum::toArray() as $type) {
  51. Cache::forget("permissions_role_{$type}");
  52. }
  53. Cache::forget("permissions_guest");
  54. $this->info('Permissions refresh completed successfully!');
  55. return Command::SUCCESS;
  56. } catch (\Exception $e) {
  57. $this->error('An error occurred while refreshing permissions:');
  58. $this->error($e);
  59. return Command::FAILURE;
  60. }
  61. }
  62. }