LaratrustSeeder.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. use Illuminate\Support\Facades\Schema;
  3. use Illuminate\Database\Seeder;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Str;
  6. use Illuminate\Support\Facades\Config;
  7. class LaratrustSeeder extends Seeder
  8. {
  9. /**
  10. * Run the database seeds.
  11. *
  12. * @return void
  13. */
  14. public function run()
  15. {
  16. $this->command->info('Truncating User, Role and Permission tables');
  17. $this->truncateLaratrustTables();
  18. $config = config('laratrust_seeder.roles_structure');
  19. $mapPermission = collect(config('laratrust_seeder.permissions_map'));
  20. foreach ($config as $key => $modules) {
  21. // Create a new role
  22. $role = \App\Role::firstOrCreate([
  23. 'name' => $key,
  24. 'display_name' => ucwords(str_replace('_', ' ', $key)),
  25. 'description' => ucwords(str_replace('_', ' ', $key))
  26. ]);
  27. $permissions = [];
  28. $this->command->info('Creating Role '. strtoupper($key));
  29. // Reading role permission modules
  30. foreach ($modules as $module => $value) {
  31. foreach (explode(',', $value) as $p => $perm) {
  32. $permissionValue = $mapPermission->get($perm);
  33. $permissions[] = \App\Permission::firstOrCreate([
  34. 'name' => $permissionValue . '-' . $module,
  35. 'display_name' => ucfirst($permissionValue) . ' ' . ucfirst($module),
  36. 'description' => ucfirst($permissionValue) . ' ' . ucfirst($module),
  37. ])->id;
  38. $this->command->info('Creating Permission to '.$permissionValue.' for '. $module);
  39. }
  40. }
  41. // Attach all permissions to the role
  42. $role->permissions()->sync($permissions);
  43. if(Config::get('laratrust_seeder.create_users')) {
  44. $this->command->info("Creating '{$key}' user");
  45. // Create default user for each role
  46. $user = \App\User::create([
  47. 'name' => ucwords(str_replace('_', ' ', $key)),
  48. 'email' => $key.'@app.com',
  49. 'password' => bcrypt('password')
  50. ]);
  51. $user->attachRole($role);
  52. }
  53. }
  54. }
  55. /**
  56. * Truncates all the laratrust tables and the users table
  57. *
  58. * @return void
  59. */
  60. public function truncateLaratrustTables()
  61. {
  62. Schema::disableForeignKeyConstraints();
  63. DB::table('permission_role')->truncate();
  64. DB::table('permission_user')->truncate();
  65. DB::table('role_user')->truncate();
  66. if(Config::get('laratrust_seeder.truncate_tables')) {
  67. \App\Role::truncate();
  68. \App\Permission::truncate();
  69. }
  70. if(Config::get('laratrust_seeder.truncate_tables') && Config::get('laratrust_seeder.create_users')) {
  71. \App\User::truncate();
  72. }
  73. Schema::enableForeignKeyConstraints();
  74. }
  75. }