feat: Add policies for SubClassification, SubLocation, and User models

- Created SubClassificationPolicy to manage authorization for SubClassification actions.
- Created SubLocationPolicy to manage authorization for SubLocation actions.
- Created UserPolicy to manage authorization for User actions.
- Integrate Filament Shield for role and permission management
- Updated DashboardPanelProvider to include FilamentShieldPlugin.
- Added filament-shield package to composer.json and updated composer.lock.
- Created filament-shield.php configuration file for Shield settings.
- Created permission.php configuration file for Spatie permissions.
- Added migration for creating permission tables.
- Created ShieldSeeder to seed roles and permissions.
- Updated DatabaseSeeder to include ShieldSeeder.
- Updated UserSeeder to assign the Developer role to the created user.
This commit is contained in:
Yoga Pangestu 2025-11-20 09:00:59 +07:00
parent 3b3a19131c
commit 28ec50494d
20 changed files with 1826 additions and 32 deletions

View File

@ -0,0 +1,31 @@
<?php
namespace App\Filament\Resources\Master\Users\Pages;
use App\Filament\Resources\Master\Users\UserResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ManageRecords;
use Filament\Support\Enums\Width;
class ManageUsers extends ManageRecords
{
protected static ?string $title = 'Pengguna';
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->label('Tambah')
->modalHeading('Tambah Pengguna')
->modalSubmitActionLabel('Simpan')
->modalCancelActionLabel('Batal')
->extraModalFooterActions(fn (CreateAction $action): array => [
$action->makeModalSubmitAction('createAnother', arguments: ['another' => true])
->label('Simpan dan Tambah Lagi'),
])
->modalWidth(Width::Large),
];
}
}

View File

@ -0,0 +1,191 @@
<?php
namespace App\Filament\Resources\Master\Users;
use App\Enums\IsActive;
use App\Filament\Resources\Master\Users\Pages\ManageUsers;
use App\Models\User;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ForceDeleteAction;
use Filament\Actions\ForceDeleteBulkAction;
use Filament\Actions\RestoreAction;
use Filament\Actions\RestoreBulkAction;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\DB;
use UnitEnum;
class UserResource extends Resource
{
protected static ?string $model = User::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::UserGroup;
protected static ?string $navigationLabel = 'Pengguna';
protected static string|UnitEnum|null $navigationGroup = 'Master';
protected static ?string $slug = 'master/users';
protected static ?string $recordTitleAttribute = 'name';
protected static ?int $navigationSort = 7;
public static function form(Schema $schema): Schema
{
return $schema
->components([
TextInput::make('name')
->label('Nama')
->placeholder('John Doe')
->autocomplete(false)
->autofocus()
->required()
->maxLength(100),
TextInput::make('email')
->label('Alamat Surel')
->placeholder('johndoe@simedkom.purwakartakab.co.id')
->autocomplete(false)
->required()
->maxLength(254)
->unique(ignoreRecord: true)
->email(),
TextInput::make('username')
->label('Nama Pengguna')
->placeholder('johndoe')
->autocomplete(false)
->required()
->minLength(5)
->maxLength(20)
->regex('/^[a-zA-Z0-9_.-]+$/')
->unique(ignoreRecord: true),
Select::make('roles')
->label('Peran')
->relationship('roles', 'name', fn ($query) => $query->where('name', '!=', 'Developer'))
->multiple()
->preload()
->searchable()
->required(),
Hidden::make('password')
->default(fn ($record) => $record ? null : config('auth.password_default')),
])
->columns(1);
}
public static function table(Table $table): Table
{
return $table
->recordTitleAttribute('name')
->columns([
TextColumn::make('name')
->label('Nama')
->searchable(),
TextColumn::make('email')
->label('Alamat Surel')
->searchable(),
TextColumn::make('username')
->label('Nama Pengguna')
->searchable(),
ToggleColumn::make('is_active')
->label('Status')
->getStateUsing(fn (User $record) => $record->is_active === IsActive::ACTIVE)
->updateStateUsing(function (User $record, bool $state) {
$record->is_active = $state ? IsActive::ACTIVE : IsActive::INACTIVE;
$record->save();
if ($record->is_active === IsActive::INACTIVE) {
DB::table('sessions')
->where('user_id', $record->id)
->delete();
}
}),
TextColumn::make('roles.name')
->label('Peran')
->getStateUsing(fn (User $record) => $record->roles->pluck('name', 'id')->toArray())
->badge()
->sortable(),
TextColumn::make('created_at')
->label('Dibuat')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('updated_at')
->label('Diperbarui')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('deleted_at')
->label('Dihapus')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
TrashedFilter::make()->native(false),
])
->recordActions([
EditAction::make()
->modalWidth(Width::Large),
DeleteAction::make(),
ForceDeleteAction::make(),
RestoreAction::make(),
])
->toolbarActions([
BulkActionGroup::make([
DeleteBulkAction::make(),
ForceDeleteBulkAction::make(),
RestoreBulkAction::make(),
]),
])
->emptyStateIcon('heroicon-o-bookmark')
->emptyStateDescription('Setelah Anda menulis posting pertama, maka akan muncul disini.')
->defaultSort('created_at', 'desc')
->deferFilters(false);
}
public static function getPages(): array
{
return [
'index' => ManageUsers::route('/'),
];
}
public static function getRecordRouteBindingEloquentQuery(): Builder
{
return parent::getRecordRouteBindingEloquentQuery()
->withoutGlobalScopes([
SoftDeletingScope::class,
]);
}
public static function getEloquentQuery(): Builder
{
return static::getModel()::query()->withoutDeveloper();
}
}

View File

@ -3,46 +3,41 @@
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Enums\IsActive;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
class User extends Authenticatable implements FilamentUser
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
use HasRoles, Notifiable, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
protected $guarded = ['id'];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'is_active' => IsActive::class,
];
}
public function canAccessPanel(Panel $panel): bool
{
return true;
}
#[Scope]
protected function withoutDeveloper(Builder $query): void
{
$query->whereDoesntHave('roles', function ($q) {
$q->where('name', 'Developer');
});
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\AiringProofTheme;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as AuthUser;
class AiringProofThemePolicy
{
use HandlesAuthorization;
public function viewAny(AuthUser $authUser): bool
{
return $authUser->can('ViewAny:AiringProofTheme');
}
public function view(AuthUser $authUser, AiringProofTheme $airingProofTheme): bool
{
return $authUser->can('View:AiringProofTheme');
}
public function create(AuthUser $authUser): bool
{
return $authUser->can('Create:AiringProofTheme');
}
public function update(AuthUser $authUser, AiringProofTheme $airingProofTheme): bool
{
return $authUser->can('Update:AiringProofTheme');
}
public function delete(AuthUser $authUser, AiringProofTheme $airingProofTheme): bool
{
return $authUser->can('Delete:AiringProofTheme');
}
public function restore(AuthUser $authUser, AiringProofTheme $airingProofTheme): bool
{
return $authUser->can('Restore:AiringProofTheme');
}
public function forceDelete(AuthUser $authUser, AiringProofTheme $airingProofTheme): bool
{
return $authUser->can('ForceDelete:AiringProofTheme');
}
public function forceDeleteAny(AuthUser $authUser): bool
{
return $authUser->can('ForceDeleteAny:AiringProofTheme');
}
public function restoreAny(AuthUser $authUser): bool
{
return $authUser->can('RestoreAny:AiringProofTheme');
}
public function replicate(AuthUser $authUser, AiringProofTheme $airingProofTheme): bool
{
return $authUser->can('Replicate:AiringProofTheme');
}
public function reorder(AuthUser $authUser): bool
{
return $authUser->can('Reorder:AiringProofTheme');
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\Classification;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as AuthUser;
class ClassificationPolicy
{
use HandlesAuthorization;
public function viewAny(AuthUser $authUser): bool
{
return $authUser->can('ViewAny:Classification');
}
public function view(AuthUser $authUser, Classification $classification): bool
{
return $authUser->can('View:Classification');
}
public function create(AuthUser $authUser): bool
{
return $authUser->can('Create:Classification');
}
public function update(AuthUser $authUser, Classification $classification): bool
{
return $authUser->can('Update:Classification');
}
public function delete(AuthUser $authUser, Classification $classification): bool
{
return $authUser->can('Delete:Classification');
}
public function restore(AuthUser $authUser, Classification $classification): bool
{
return $authUser->can('Restore:Classification');
}
public function forceDelete(AuthUser $authUser, Classification $classification): bool
{
return $authUser->can('ForceDelete:Classification');
}
public function forceDeleteAny(AuthUser $authUser): bool
{
return $authUser->can('ForceDeleteAny:Classification');
}
public function restoreAny(AuthUser $authUser): bool
{
return $authUser->can('RestoreAny:Classification');
}
public function replicate(AuthUser $authUser, Classification $classification): bool
{
return $authUser->can('Replicate:Classification');
}
public function reorder(AuthUser $authUser): bool
{
return $authUser->can('Reorder:Classification');
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\Department;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as AuthUser;
class DepartmentPolicy
{
use HandlesAuthorization;
public function viewAny(AuthUser $authUser): bool
{
return $authUser->can('ViewAny:Department');
}
public function view(AuthUser $authUser, Department $department): bool
{
return $authUser->can('View:Department');
}
public function create(AuthUser $authUser): bool
{
return $authUser->can('Create:Department');
}
public function update(AuthUser $authUser, Department $department): bool
{
return $authUser->can('Update:Department');
}
public function delete(AuthUser $authUser, Department $department): bool
{
return $authUser->can('Delete:Department');
}
public function restore(AuthUser $authUser, Department $department): bool
{
return $authUser->can('Restore:Department');
}
public function forceDelete(AuthUser $authUser, Department $department): bool
{
return $authUser->can('ForceDelete:Department');
}
public function forceDeleteAny(AuthUser $authUser): bool
{
return $authUser->can('ForceDeleteAny:Department');
}
public function restoreAny(AuthUser $authUser): bool
{
return $authUser->can('RestoreAny:Department');
}
public function replicate(AuthUser $authUser, Department $department): bool
{
return $authUser->can('Replicate:Department');
}
public function reorder(AuthUser $authUser): bool
{
return $authUser->can('Reorder:Department');
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\Location;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as AuthUser;
class LocationPolicy
{
use HandlesAuthorization;
public function viewAny(AuthUser $authUser): bool
{
return $authUser->can('ViewAny:Location');
}
public function view(AuthUser $authUser, Location $location): bool
{
return $authUser->can('View:Location');
}
public function create(AuthUser $authUser): bool
{
return $authUser->can('Create:Location');
}
public function update(AuthUser $authUser, Location $location): bool
{
return $authUser->can('Update:Location');
}
public function delete(AuthUser $authUser, Location $location): bool
{
return $authUser->can('Delete:Location');
}
public function restore(AuthUser $authUser, Location $location): bool
{
return $authUser->can('Restore:Location');
}
public function forceDelete(AuthUser $authUser, Location $location): bool
{
return $authUser->can('ForceDelete:Location');
}
public function forceDeleteAny(AuthUser $authUser): bool
{
return $authUser->can('ForceDeleteAny:Location');
}
public function restoreAny(AuthUser $authUser): bool
{
return $authUser->can('RestoreAny:Location');
}
public function replicate(AuthUser $authUser, Location $location): bool
{
return $authUser->can('Replicate:Location');
}
public function reorder(AuthUser $authUser): bool
{
return $authUser->can('Reorder:Location');
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as AuthUser;
use Spatie\Permission\Models\Role;
class RolePolicy
{
use HandlesAuthorization;
public function viewAny(AuthUser $authUser): bool
{
return $authUser->can('ViewAny:Role');
}
public function view(AuthUser $authUser, Role $role): bool
{
return $authUser->can('View:Role');
}
public function create(AuthUser $authUser): bool
{
return $authUser->can('Create:Role');
}
public function update(AuthUser $authUser, Role $role): bool
{
return $authUser->can('Update:Role');
}
public function delete(AuthUser $authUser, Role $role): bool
{
return $authUser->can('Delete:Role');
}
public function restore(AuthUser $authUser, Role $role): bool
{
return $authUser->can('Restore:Role');
}
public function forceDelete(AuthUser $authUser, Role $role): bool
{
return $authUser->can('ForceDelete:Role');
}
public function forceDeleteAny(AuthUser $authUser): bool
{
return $authUser->can('ForceDeleteAny:Role');
}
public function restoreAny(AuthUser $authUser): bool
{
return $authUser->can('RestoreAny:Role');
}
public function replicate(AuthUser $authUser, Role $role): bool
{
return $authUser->can('Replicate:Role');
}
public function reorder(AuthUser $authUser): bool
{
return $authUser->can('Reorder:Role');
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\SubClassification;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as AuthUser;
class SubClassificationPolicy
{
use HandlesAuthorization;
public function viewAny(AuthUser $authUser): bool
{
return $authUser->can('ViewAny:SubClassification');
}
public function view(AuthUser $authUser, SubClassification $subClassification): bool
{
return $authUser->can('View:SubClassification');
}
public function create(AuthUser $authUser): bool
{
return $authUser->can('Create:SubClassification');
}
public function update(AuthUser $authUser, SubClassification $subClassification): bool
{
return $authUser->can('Update:SubClassification');
}
public function delete(AuthUser $authUser, SubClassification $subClassification): bool
{
return $authUser->can('Delete:SubClassification');
}
public function restore(AuthUser $authUser, SubClassification $subClassification): bool
{
return $authUser->can('Restore:SubClassification');
}
public function forceDelete(AuthUser $authUser, SubClassification $subClassification): bool
{
return $authUser->can('ForceDelete:SubClassification');
}
public function forceDeleteAny(AuthUser $authUser): bool
{
return $authUser->can('ForceDeleteAny:SubClassification');
}
public function restoreAny(AuthUser $authUser): bool
{
return $authUser->can('RestoreAny:SubClassification');
}
public function replicate(AuthUser $authUser, SubClassification $subClassification): bool
{
return $authUser->can('Replicate:SubClassification');
}
public function reorder(AuthUser $authUser): bool
{
return $authUser->can('Reorder:SubClassification');
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\SubLocation;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as AuthUser;
class SubLocationPolicy
{
use HandlesAuthorization;
public function viewAny(AuthUser $authUser): bool
{
return $authUser->can('ViewAny:SubLocation');
}
public function view(AuthUser $authUser, SubLocation $subLocation): bool
{
return $authUser->can('View:SubLocation');
}
public function create(AuthUser $authUser): bool
{
return $authUser->can('Create:SubLocation');
}
public function update(AuthUser $authUser, SubLocation $subLocation): bool
{
return $authUser->can('Update:SubLocation');
}
public function delete(AuthUser $authUser, SubLocation $subLocation): bool
{
return $authUser->can('Delete:SubLocation');
}
public function restore(AuthUser $authUser, SubLocation $subLocation): bool
{
return $authUser->can('Restore:SubLocation');
}
public function forceDelete(AuthUser $authUser, SubLocation $subLocation): bool
{
return $authUser->can('ForceDelete:SubLocation');
}
public function forceDeleteAny(AuthUser $authUser): bool
{
return $authUser->can('ForceDeleteAny:SubLocation');
}
public function restoreAny(AuthUser $authUser): bool
{
return $authUser->can('RestoreAny:SubLocation');
}
public function replicate(AuthUser $authUser, SubLocation $subLocation): bool
{
return $authUser->can('Replicate:SubLocation');
}
public function reorder(AuthUser $authUser): bool
{
return $authUser->can('Reorder:SubLocation');
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace App\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as AuthUser;
class UserPolicy
{
use HandlesAuthorization;
public function viewAny(AuthUser $authUser): bool
{
return $authUser->can('ViewAny:User');
}
public function view(AuthUser $authUser): bool
{
return $authUser->can('View:User');
}
public function create(AuthUser $authUser): bool
{
return $authUser->can('Create:User');
}
public function update(AuthUser $authUser): bool
{
return $authUser->can('Update:User');
}
public function delete(AuthUser $authUser): bool
{
return $authUser->can('Delete:User');
}
public function restore(AuthUser $authUser): bool
{
return $authUser->can('Restore:User');
}
public function forceDelete(AuthUser $authUser): bool
{
return $authUser->can('ForceDelete:User');
}
public function forceDeleteAny(AuthUser $authUser): bool
{
return $authUser->can('ForceDeleteAny:User');
}
public function restoreAny(AuthUser $authUser): bool
{
return $authUser->can('RestoreAny:User');
}
public function replicate(AuthUser $authUser): bool
{
return $authUser->can('Replicate:User');
}
public function reorder(AuthUser $authUser): bool
{
return $authUser->can('Reorder:User');
}
}

View File

@ -3,6 +3,7 @@
namespace App\Providers\Filament;
use App\Filament\Pages\CustomLogin;
use BezhanSalleh\FilamentShield\FilamentShieldPlugin;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
@ -56,6 +57,11 @@ public function panel(Panel $panel): Panel
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
])
->plugins([
FilamentShieldPlugin::make()
->navigationSort(10)
->globallySearchable(false),
])
->authMiddleware([
Authenticate::class,
])

View File

@ -7,6 +7,7 @@
"license": "MIT",
"require": {
"php": "^8.2",
"bezhansalleh/filament-shield": "^4.0",
"filament/filament": "^4.0",
"laravel/framework": "^12.0",
"laravel/tinker": "^2.10.1"

257
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "d06fce5a31d9da3c576b967652ed06de",
"content-hash": "aa7873cd5d15f6140efb985c4ea9d50d",
"packages": [
{
"name": "anourvalar/eloquent-serialize",
@ -72,6 +72,178 @@
},
"time": "2025-07-30T15:45:57+00:00"
},
{
"name": "bezhansalleh/filament-plugin-essentials",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/bezhanSalleh/filament-plugin-essentials.git",
"reference": "fb4656c661270133b1b1c4297616745e4d586ca7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/bezhanSalleh/filament-plugin-essentials/zipball/fb4656c661270133b1b1c4297616745e4d586ca7",
"reference": "fb4656c661270133b1b1c4297616745e4d586ca7",
"shasum": ""
},
"require": {
"filament/filament": "^4.0",
"illuminate/contracts": "^11.28|^12.0",
"php": "^8.2",
"spatie/laravel-package-tools": "^1.9"
},
"require-dev": {
"larastan/larastan": "^2.9||^3.0",
"laravel/pint": "^1.14",
"nunomaduro/collision": "^8.1.1||^7.10.0",
"orchestra/testbench": "^10.0.0||^9.0.0",
"pestphp/pest": "^3.0",
"pestphp/pest-plugin-arch": "^3.0",
"pestphp/pest-plugin-laravel": "^3.0",
"pestphp/pest-plugin-type-coverage": "^3.5",
"phpstan/extension-installer": "^1.3||^2.0",
"phpstan/phpstan-deprecation-rules": "^1.1||^2.0",
"phpstan/phpstan-phpunit": "^1.3||^2.0",
"rector/rector": "^2.1",
"spatie/laravel-ray": "^1.40"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"BezhanSalleh\\PluginEssentials\\PluginEssentialsServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"BezhanSalleh\\PluginEssentials\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bezhan Salleh",
"email": "bezhan_salleh@yahoo.com",
"role": "Developer"
}
],
"description": "A collection of essential traits that streamline Filament plugin development by taking care of the boilerplate, so you can focus on shipping real features faster",
"homepage": "https://github.com/bezhansalleh/filament-plugin-essentials",
"keywords": [
"Bezhan Salleh",
"filament-plugin-essentials",
"laravel"
],
"support": {
"issues": "https://github.com/bezhanSalleh/filament-plugin-essentials/issues",
"source": "https://github.com/bezhanSalleh/filament-plugin-essentials/tree/1.0.0"
},
"funding": [
{
"url": "https://github.com/bezhanSalleh",
"type": "github"
}
],
"time": "2025-08-31T06:50:44+00:00"
},
{
"name": "bezhansalleh/filament-shield",
"version": "4.0.2",
"source": {
"type": "git",
"url": "https://github.com/bezhanSalleh/filament-shield.git",
"reference": "1c7b21dbac1e80bb05a409c9b13926c13ff210ab"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/bezhanSalleh/filament-shield/zipball/1c7b21dbac1e80bb05a409c9b13926c13ff210ab",
"reference": "1c7b21dbac1e80bb05a409c9b13926c13ff210ab",
"shasum": ""
},
"require": {
"bezhansalleh/filament-plugin-essentials": "^1.0",
"filament/filament": "^4.0",
"illuminate/contracts": "^11.28|^12.0",
"illuminate/support": "*",
"php": "^8.2",
"spatie/laravel-package-tools": "^1.9",
"spatie/laravel-permission": "^6.0"
},
"require-dev": {
"larastan/larastan": "^2.2|^3.0",
"laravel/pint": "^1.0",
"nunomaduro/collision": "^7.0|^8.0",
"orchestra/testbench": "^8.0|^9.0|^10.0",
"pestphp/pest": "^2.0|^3.0",
"pestphp/pest-plugin-laravel": "^2.0|^3.0",
"pestphp/pest-plugin-livewire": "^3.0",
"pestphp/pest-plugin-type-coverage": "^3.5",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan": "^2.1",
"phpstan/phpstan-deprecation-rules": "^2.0",
"phpstan/phpstan-phpunit": "^2.0",
"phpunit/phpunit": "^10.1|^11.0",
"rector/rector": "^2.1",
"spatie/laravel-ray": "^1.40"
},
"type": "library",
"extra": {
"laravel": {
"aliases": {
"FilamentShield": "BezhanSalleh\\FilamentShield\\Facades\\FilamentShield"
},
"providers": [
"BezhanSalleh\\FilamentShield\\FilamentShieldServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"BezhanSalleh\\FilamentShield\\": "src",
"BezhanSalleh\\FilamentShield\\Database\\Factories\\": "database/factories"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bezhan Salleh",
"email": "bezhan_salleh@yahoo.com",
"role": "Developer"
}
],
"description": "Filament support for `spatie/laravel-permission`.",
"homepage": "https://github.com/bezhansalleh/filament-shield",
"keywords": [
"acl",
"bezhanSalleh",
"filament",
"filament-shield",
"laravel",
"permission",
"permissions",
"rbac",
"roles",
"security"
],
"support": {
"issues": "https://github.com/bezhanSalleh/filament-shield/issues",
"source": "https://github.com/bezhanSalleh/filament-shield/tree/4.0.2"
},
"funding": [
{
"url": "https://github.com/bezhanSalleh",
"type": "github"
}
],
"time": "2025-09-11T02:13:12+00:00"
},
{
"name": "blade-ui-kit/blade-heroicons",
"version": "2.6.0",
@ -5206,6 +5378,89 @@
],
"time": "2025-07-17T15:46:43+00:00"
},
{
"name": "spatie/laravel-permission",
"version": "6.23.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-permission.git",
"reference": "9e41247bd512b1e6c229afbc1eb528f7565ae3bb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-permission/zipball/9e41247bd512b1e6c229afbc1eb528f7565ae3bb",
"reference": "9e41247bd512b1e6c229afbc1eb528f7565ae3bb",
"shasum": ""
},
"require": {
"illuminate/auth": "^8.12|^9.0|^10.0|^11.0|^12.0",
"illuminate/container": "^8.12|^9.0|^10.0|^11.0|^12.0",
"illuminate/contracts": "^8.12|^9.0|^10.0|^11.0|^12.0",
"illuminate/database": "^8.12|^9.0|^10.0|^11.0|^12.0",
"php": "^8.0"
},
"require-dev": {
"laravel/passport": "^11.0|^12.0",
"laravel/pint": "^1.0",
"orchestra/testbench": "^6.23|^7.0|^8.0|^9.0|^10.0",
"phpunit/phpunit": "^9.4|^10.1|^11.5"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Spatie\\Permission\\PermissionServiceProvider"
]
},
"branch-alias": {
"dev-main": "6.x-dev",
"dev-master": "6.x-dev"
}
},
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"Spatie\\Permission\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "Permission handling for Laravel 8.0 and up",
"homepage": "https://github.com/spatie/laravel-permission",
"keywords": [
"acl",
"laravel",
"permission",
"permissions",
"rbac",
"roles",
"security",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/laravel-permission/issues",
"source": "https://github.com/spatie/laravel-permission/tree/6.23.0"
},
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2025-11-03T20:16:13+00:00"
},
{
"name": "spatie/shiki-php",
"version": "2.3.2",

261
config/filament-shield.php Normal file
View File

@ -0,0 +1,261 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Shield Resource
|--------------------------------------------------------------------------
|
| Here you may configure the built-in role management resource. You can
| customize the URL, choose whether to show model paths, group it under
| a cluster, and decide which permission tabs to display.
|
*/
'shield_resource' => [
'slug' => 'shield/roles',
'show_model_path' => true,
'cluster' => null,
'tabs' => [
'pages' => true,
'widgets' => true,
'resources' => true,
'custom_permissions' => false,
],
],
/*
|--------------------------------------------------------------------------
| Multi-Tenancy
|--------------------------------------------------------------------------
|
| When your application supports teams, Shield will automatically detect
| and configure the tenant model during setup. This enables tenant-scoped
| roles and permissions throughout your application.
|
*/
'tenant_model' => null,
/*
|--------------------------------------------------------------------------
| User Model
|--------------------------------------------------------------------------
|
| This value contains the class name of your user model. This model will
| be used for role assignments and must implement the HasRoles trait
| provided by the Spatie\Permission package.
|
*/
'auth_provider_model' => 'App\\Models\\User',
/*
|--------------------------------------------------------------------------
| Super Admin
|--------------------------------------------------------------------------
|
| Here you may define a super admin that has unrestricted access to your
| application. You can choose to implement this via Laravel's gate system
| or as a traditional role with all permissions explicitly assigned.
|
*/
'super_admin' => [
'enabled' => true,
'name' => 'super_admin',
'define_via_gate' => false,
'intercept_gate' => 'before',
],
/*
|--------------------------------------------------------------------------
| Panel User
|--------------------------------------------------------------------------
|
| When enabled, Shield will create a basic panel user role that can be
| assigned to users who should have access to your Filament panels but
| don't need any specific permissions beyond basic authentication.
|
*/
'panel_user' => [
'enabled' => true,
'name' => 'panel_user',
],
/*
|--------------------------------------------------------------------------
| Permission Builder
|--------------------------------------------------------------------------
|
| You can customize how permission keys are generated to match your
| preferred naming convention and organizational standards. Shield uses
| these settings when creating permission names from your resources.
|
| Supported formats: snake, kebab, pascal, camel, upper_snake, lower_snake
|
*/
'permissions' => [
'separator' => ':',
'case' => 'pascal',
'generate' => true,
],
/*
|--------------------------------------------------------------------------
| Policies
|--------------------------------------------------------------------------
|
| Shield can automatically generate Laravel policies for your resources.
| When merge is enabled, the methods below will be combined with any
| resource-specific methods you define in the resources section.
|
*/
'policies' => [
'path' => app_path('Policies'),
'merge' => true,
'generate' => true,
'methods' => [
'viewAny', 'view', 'create', 'update', 'delete', 'restore',
'forceDelete', 'forceDeleteAny', 'restoreAny', 'replicate', 'reorder',
],
'single_parameter_methods' => [
'viewAny',
'create',
'deleteAny',
'forceDeleteAny',
'restoreAny',
'reorder',
],
],
/*
|--------------------------------------------------------------------------
| Localization
|--------------------------------------------------------------------------
|
| Shield supports multiple languages out of the box. When enabled, you
| can provide translated labels for permissions to create a more
| localized experience for your international users.
|
*/
'localization' => [
'enabled' => false,
'key' => 'filament-shield::filament-shield',
],
/*
|--------------------------------------------------------------------------
| Resources
|--------------------------------------------------------------------------
|
| Here you can fine-tune permissions for specific Filament resources.
| Use the 'manage' array to override the default policy methods for
| individual resources, giving you granular control over permissions.
|
*/
'resources' => [
'subject' => 'model',
'manage' => [
\BezhanSalleh\FilamentShield\Resources\Roles\RoleResource::class => [
'viewAny',
'view',
'create',
'update',
'delete',
],
],
'exclude' => [
//
],
],
/*
|--------------------------------------------------------------------------
| Pages
|--------------------------------------------------------------------------
|
| Most Filament pages only require view permissions. Pages listed in the
| exclude array will be skipped during permission generation and won't
| appear in your role management interface.
|
*/
'pages' => [
'subject' => 'class',
'prefix' => 'view',
'exclude' => [
\Filament\Pages\Dashboard::class,
],
],
/*
|--------------------------------------------------------------------------
| Widgets
|--------------------------------------------------------------------------
|
| Like pages, widgets typically only need view permissions. Add widgets
| to the exclude array if you don't want them to appear in your role
| management interface.
|
*/
'widgets' => [
'subject' => 'class',
'prefix' => 'view',
'exclude' => [
\Filament\Widgets\AccountWidget::class,
\Filament\Widgets\FilamentInfoWidget::class,
],
],
/*
|--------------------------------------------------------------------------
| Custom Permissions
|--------------------------------------------------------------------------
|
| Sometimes you need permissions that don't map to resources, pages, or
| widgets. Define any custom permissions here and they'll be available
| when editing roles in your application.
|
*/
'custom_permissions' => [],
/*
|--------------------------------------------------------------------------
| Entity Discovery
|--------------------------------------------------------------------------
|
| By default, Shield only looks for entities in your default Filament
| panel. Enable these options if you're using multiple panels and want
| Shield to discover entities across all of them.
|
*/
'discovery' => [
'discover_all_resources' => false,
'discover_all_widgets' => false,
'discover_all_pages' => false,
],
/*
|--------------------------------------------------------------------------
| Role Policy
|--------------------------------------------------------------------------
|
| Shield can automatically register a policy for role management itself.
| This lets you control who can manage roles using Laravel's built-in
| authorization system. Requires a RolePolicy class in your app.
|
*/
'register_role_policy' => true,
];

202
config/permission.php Normal file
View File

@ -0,0 +1,202 @@
<?php
return [
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => Spatie\Permission\Models\Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => Spatie\Permission\Models\Role::class,
],
'table_names' => [
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'roles' => 'roles',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your permissions. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'permissions' => 'permissions',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your models permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_permissions' => 'model_has_permissions',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your models roles. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_roles' => 'model_has_roles',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'role_has_permissions' => 'role_has_permissions',
],
'column_names' => [
/*
* Change this if you want to name the related pivots other than defaults
*/
'role_pivot_key' => null, // default 'role_id',
'permission_pivot_key' => null, // default 'permission_id',
/*
* Change this if you want to name the related model primary key other than
* `model_id`.
*
* For example, this would be nice if your primary keys are all UUIDs. In
* that case, name this `model_uuid`.
*/
'model_morph_key' => 'model_id',
/*
* Change this if you want to use the teams feature and your related model's
* foreign key is other than `team_id`.
*/
'team_foreign_key' => 'team_id',
],
/*
* When set to true, the method for checking permissions will be registered on the gate.
* Set this to false if you want to implement custom logic for checking permissions.
*/
'register_permission_check_method' => true,
/*
* When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered
* this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated
* NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it.
*/
'register_octane_reset_listener' => false,
/*
* Events will fire when a role or permission is assigned/unassigned:
* \Spatie\Permission\Events\RoleAttached
* \Spatie\Permission\Events\RoleDetached
* \Spatie\Permission\Events\PermissionAttached
* \Spatie\Permission\Events\PermissionDetached
*
* To enable, set to true, and then create listeners to watch these events.
*/
'events_enabled' => false,
/*
* Teams Feature.
* When set to true the package implements teams using the 'team_foreign_key'.
* If you want the migrations to register the 'team_foreign_key', you must
* set this to true before doing the migration.
* If you already did the migration then you must make a new migration to also
* add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions'
* (view the latest version of this package's migration file)
*/
'teams' => false,
/*
* The class to use to resolve the permissions team id
*/
'team_resolver' => \Spatie\Permission\DefaultTeamResolver::class,
/*
* Passport Client Credentials Grant
* When set to true the package will use Passports Client to check permissions
*/
'use_passport_client_credentials' => false,
/*
* When set to true, the required permission names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_permission_in_exception' => false,
/*
* When set to true, the required role names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_role_in_exception' => false,
/*
* By default wildcard permission lookups are disabled.
* See documentation to understand supported syntax.
*/
'enable_wildcard_permission' => false,
/*
* The class to use for interpreting wildcard permissions.
* If you need to modify delimiters, override the class and specify its name here.
*/
// 'wildcard_permission' => Spatie\Permission\WildcardPermission::class,
/* Cache-specific settings */
'cache' => [
/*
* By default all permissions are cached for 24 hours to speed up performance.
* When permissions or roles are updated the cache is flushed automatically.
*/
'expiration_time' => \DateInterval::createFromDateString('24 hours'),
/*
* The cache key used to store all permissions.
*/
'key' => 'spatie.permission.cache',
/*
* You may optionally indicate a specific cache driver to use for permission and
* role caching using any of the `store` drivers listed in the cache.php config
* file. Using 'default' here means to use the `default` set in cache.php.
*/
'store' => 'default',
],
];

View File

@ -0,0 +1,134 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$teams = config('permission.teams');
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';
$pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), Exception::class, 'Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
Schema::create($tableNames['permissions'], static function (Blueprint $table) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // permission id
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
$table->unique(['name', 'guard_name']);
});
Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
$table->unsignedBigInteger($pivotPermission);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
$table->unsignedBigInteger($pivotRole);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
$table->unsignedBigInteger($pivotPermission);
$table->unsignedBigInteger($pivotRole);
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$tableNames = config('permission.table_names');
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
Schema::drop($tableNames['role_has_permissions']);
Schema::drop($tableNames['model_has_roles']);
Schema::drop($tableNames['model_has_permissions']);
Schema::drop($tableNames['roles']);
Schema::drop($tableNames['permissions']);
}
};

View File

@ -15,6 +15,7 @@ class DatabaseSeeder extends Seeder
public function run(): void
{
$this->call([
ShieldSeeder::class,
UserSeeder::class,
]);
}

View File

@ -0,0 +1,166 @@
<?php
namespace Database\Seeders;
use BezhanSalleh\FilamentShield\Support\Utils;
use Illuminate\Database\Seeder;
use Spatie\Permission\PermissionRegistrar;
class ShieldSeeder extends Seeder
{
public function run(): void
{
app()[PermissionRegistrar::class]->forgetCachedPermissions();
$rolesWithPermissions = <<<'JSON'
[
{
"name": "Developer",
"guard_name": "web",
"permissions": [
"ViewAny:Role",
"View:Role",
"Create:Role",
"Update:Role",
"Delete:Role",
"Restore:Role",
"ForceDelete:Role",
"ForceDeleteAny:Role",
"RestoreAny:Role",
"Replicate:Role",
"Reorder:Role",
"ViewAny:AiringProofTheme",
"View:AiringProofTheme",
"Create:AiringProofTheme",
"Update:AiringProofTheme",
"Delete:AiringProofTheme",
"Restore:AiringProofTheme",
"ForceDelete:AiringProofTheme",
"ForceDeleteAny:AiringProofTheme",
"RestoreAny:AiringProofTheme",
"Replicate:AiringProofTheme",
"Reorder:AiringProofTheme",
"ViewAny:Classification",
"View:Classification",
"Create:Classification",
"Update:Classification",
"Delete:Classification",
"Restore:Classification",
"ForceDelete:Classification",
"ForceDeleteAny:Classification",
"RestoreAny:Classification",
"Replicate:Classification",
"Reorder:Classification",
"ViewAny:Department",
"View:Department",
"Create:Department",
"Update:Department",
"Delete:Department",
"Restore:Department",
"ForceDelete:Department",
"ForceDeleteAny:Department",
"RestoreAny:Department",
"Replicate:Department",
"Reorder:Department",
"ViewAny:Location",
"View:Location",
"Create:Location",
"Update:Location",
"Delete:Location",
"Restore:Location",
"ForceDelete:Location",
"ForceDeleteAny:Location",
"RestoreAny:Location",
"Replicate:Location",
"Reorder:Location",
"ViewAny:SubClassification",
"View:SubClassification",
"Create:SubClassification",
"Update:SubClassification",
"Delete:SubClassification",
"Restore:SubClassification",
"ForceDelete:SubClassification",
"ForceDeleteAny:SubClassification",
"RestoreAny:SubClassification",
"Replicate:SubClassification",
"Reorder:SubClassification",
"ViewAny:SubLocation",
"View:SubLocation",
"Create:SubLocation",
"Update:SubLocation",
"Delete:SubLocation",
"Restore:SubLocation",
"ForceDelete:SubLocation",
"ForceDeleteAny:SubLocation",
"RestoreAny:SubLocation",
"Replicate:SubLocation",
"Reorder:SubLocation",
"ViewAny:User",
"View:User",
"Create:User",
"Update:User",
"Delete:User",
"Restore:User",
"ForceDelete:User",
"ForceDeleteAny:User",
"RestoreAny:User",
"Replicate:User",
"Reorder:User"
]
}
]
JSON;
$directPermissions = '[]';
static::makeRolesWithPermissions($rolesWithPermissions);
static::makeDirectPermissions($directPermissions);
$this->command->info('Shield Seeding Completed.');
}
protected static function makeRolesWithPermissions(string $rolesWithPermissions): void
{
if (! blank($rolePlusPermissions = json_decode($rolesWithPermissions, true))) {
/** @var Model $roleModel */
$roleModel = Utils::getRoleModel();
/** @var Model $permissionModel */
$permissionModel = Utils::getPermissionModel();
foreach ($rolePlusPermissions as $rolePlusPermission) {
$role = $roleModel::firstOrCreate([
'name' => $rolePlusPermission['name'],
'guard_name' => $rolePlusPermission['guard_name'],
]);
if (! blank($rolePlusPermission['permissions'])) {
$permissionModels = collect($rolePlusPermission['permissions'])
->map(fn ($permission) => $permissionModel::firstOrCreate([
'name' => $permission,
'guard_name' => $rolePlusPermission['guard_name'],
]))
->all();
$role->syncPermissions($permissionModels);
}
}
}
}
public static function makeDirectPermissions(string $directPermissions): void
{
if (! blank($permissions = json_decode($directPermissions, true))) {
/** @var Model $permissionModel */
$permissionModel = Utils::getPermissionModel();
foreach ($permissions as $permission) {
if ($permissionModel::whereName($permission)->doesntExist()) {
$permissionModel::create([
'name' => $permission['name'],
'guard_name' => $permission['guard_name'],
]);
}
}
}
}
}

View File

@ -13,11 +13,13 @@ class UserSeeder extends Seeder
*/
public function run(): void
{
User::create([
$user = User::create([
'name' => 'Yoga Pangestu',
'email' => 'info.pangestuyoga@gmail.com',
'username' => 'pangestu',
'password' => Hash::make(config('auth.password_default')),
]);
$user->assignRole('Developer');
}
}