Created
September 13, 2022 07:07
-
-
Save vidux/2b7050232573666b54ec1bbfb0ab1a49 to your computer and use it in GitHub Desktop.
Laravel Permission Seeder Improved
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 | |
//https://github.com/vidux/ | |
//check more at https://gist.github.com/vidux | |
namespace Database\Seeders; | |
use Spatie\Permission\Models\Permission; | |
use Illuminate\Database\Seeder; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Support\Facades\Schema; | |
class PermissionSeeder extends Seeder | |
{ | |
/** | |
* Run the database seeds. | |
* | |
* @return void | |
*/ | |
public $count = 0; | |
public function run() | |
{ | |
//forget permission cache | |
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions(); | |
DB::beginTransaction(); | |
try { | |
//code... | |
Schema::disableForeignKeyConstraints(); | |
DB::table('role_has_permissions')->truncate(); | |
Permission::truncate(); | |
// user manange permissions | |
$this->createPermission(['name' => 'user_create', 'description' => 'create user']); | |
$this->createPermission(['name' => 'user_edit', 'description' => 'edit user details']); | |
$this->createPermission(['name' => 'user_delete', 'description' => 'delete user']); | |
$this->createPermission(['name' => 'user_view', 'description' => 'view user']); | |
//add more permissions like above (remove description column data if your table desent have that column) | |
Schema::enableForeignKeyConstraints(); | |
DB::commit(); | |
echo "$this->count permissions added!\n"; | |
} catch (\Throwable $th) { | |
DB::rollBack(); | |
throw $th; | |
} | |
} | |
public function createPermission(array $permissionData) | |
{ | |
//check is already exist | |
$permission = Permission::where('name', $permissionData['name'])->exists(); | |
if (!$permission) { | |
Permission::create($permissionData); | |
$this->count++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment