Last active
September 1, 2024 13:06
-
-
Save awcodes/050840536b052a6cd87c1d337773424a to your computer and use it in GitHub Desktop.
Shield Seeders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Database\Seeders; | |
use Illuminate\Database\Seeder; | |
use Illuminate\Support\Facades\Artisan; | |
use Spatie\Permission\Models\Permission; | |
use Spatie\Permission\Models\Role; | |
class PermissionSeeder extends Seeder | |
{ | |
public function run(): void | |
{ | |
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions(); | |
$superAdmin = Role::create(['name' => 'super_admin']); | |
$admin = Role::create(['name' => 'admin']); | |
$editor = Role::create(['name' => 'editor']); | |
Artisan::call('shield:generate', ['--all' => true]); | |
$superAdmin->givePermissionTo(Permission::all()); | |
$admin->givePermissionTo(Permission::where('name', 'not like', '%_role')->get()); | |
$editor->givePermissionTo( | |
Permission::query() | |
->where('name', 'not like', '%_role') | |
->where('name', 'not like', '%_user') | |
->where('name', 'not like', '%_redirect') | |
->where('name', 'not like', '%_redirect::group') | |
->where('name', 'not like', '%_redirect404') | |
->get() | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Database\Seeders; | |
use App\Models\User; | |
use Illuminate\Database\Console\Seeds\WithoutModelEvents; | |
use Illuminate\Database\Seeder; | |
class UserSeeder extends Seeder | |
{ | |
use WithoutModelEvents; | |
/** | |
* Run the database seeds. | |
* | |
* @return void | |
*/ | |
public function run(): void | |
{ | |
$users = [ | |
[ | |
'name' => 'Super User', | |
'email' => '[email protected]', | |
'roles' => 'super_admin', | |
], | |
[ | |
'name' => 'Admin User', | |
'email' => '[email protected]', | |
'roles' => 'admin', | |
], | |
[ | |
'name' => 'Editor', | |
'email' => '[email protected]', | |
'roles' => 'editor', | |
], | |
]; | |
foreach ($users as $user) { | |
User::factory()->create([ | |
'name' => $user['name'], | |
'email' => $user['email'], | |
])->assignRole($user['roles']); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment