AdminUserRoleAndPermissionTableSeeder.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. use App\Models\AdminPermission;
  3. use App\Models\AdminRole;
  4. use App\Models\AdminUser;
  5. use Illuminate\Database\Seeder;
  6. class AdminUserRoleAndPermissionTableSeeder extends Seeder
  7. {
  8. /**
  9. * Run the database seeds.
  10. *
  11. * @return void
  12. */
  13. public function run()
  14. {
  15. $users = AdminUser::all();
  16. if ($users->isEmpty()) {
  17. $this->call(AdminUsersTableSeeder::class);
  18. $users = AdminUser::all();
  19. }
  20. $roles = AdminRole::pluck('id');
  21. if ($roles->isEmpty()) {
  22. $this->call(AdminRolesTableSeeder::class);
  23. $roles = AdminRole::pluck('id');
  24. }
  25. $perms = AdminPermission::pluck('id');
  26. if ($perms->isEmpty()) {
  27. $this->call(AdminPermissionsTableSeeder::class);
  28. $perms = AdminPermission::pluck('id');
  29. }
  30. $faker = app(Faker\Generator::class);
  31. $users->each(function (AdminUser $user) use ($faker, $roles) {
  32. $user->roles()
  33. ->attach($faker->randomElements($roles, $faker->numberBetween(0, 5)));
  34. });
  35. $users->each(function (AdminUser $user) use ($faker, $perms) {
  36. $user->permissions()
  37. ->attach($faker->randomElements($perms, $faker->numberBetween(0, 5)));
  38. });
  39. }
  40. }