feat: Add comprehensive user, role, and permission management through Filament Shield integration.

This commit is contained in:
Yoga Pangestu 2026-02-09 09:13:07 +07:00
parent 78e8de28d7
commit 0a23f4d0e3
13 changed files with 1356 additions and 2 deletions

View File

@ -0,0 +1,42 @@
<?php
namespace App\Filament\Resources\Master\Users\Actions;
use App\Filament\Support\CheerfulNotification;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Forms\Components\TextInput;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Hash;
class ChangePasswordAction extends Action
{
protected function setUp(): void
{
parent::setUp();
$this->label('Ganti Kata Sandi')
->icon(Heroicon::Key)
->color('warning')
->modalWidth(Width::Medium)
->schema([
TextInput::make('password')
->label('Kata Sandi Baru')
->password()
->required()
->minLength(8)
->default(config('auth.password_default')),
])
->action(function (User $record, array $data): void {
$record->update([
'password' => Hash::make($data['password']),
]);
CheerfulNotification::success(
'Kata sandi berhasil diubah! 🔑',
"Kata sandi untuk pengguna {$record->name} telah diperbarui."
)->send();
});
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Filament\Resources\Master\Users\Pages;
use App\Filament\Actions\Cheerful\CreateAction;
use App\Filament\Resources\Master\Users\UserResource;
use Filament\Resources\Pages\ManageRecords;
use Filament\Support\Enums\Width;
class ManageUsers extends ManageRecords
{
protected static string $resource = UserResource::class;
protected static ?string $title = 'Pengguna';
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)
->after(function (CreateAction $action): void {
$user = $action->getRecord();
$user->update([
'email_verified_at' => now(),
]);
}),
];
}
}

View File

@ -0,0 +1,170 @@
<?php
namespace App\Filament\Resources\Master\Users;
use App\Enums\RoleEnum;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use App\Filament\Resources\Master\Users\Actions\ChangePasswordAction;
use App\Filament\Resources\Master\Users\Pages\ManageUsers;
use App\Models\User;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
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\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use UnitEnum;
class UserResource extends Resource
{
protected static ?string $model = User::class;
protected static string|UnitEnum|null $navigationGroup = 'Master';
protected static string|BackedEnum|null $navigationIcon = Heroicon::UserGroup;
protected static ?string $navigationLabel = 'Pengguna';
protected static ?int $navigationSort = 8;
protected static ?string $recordTitleAttribute = 'name';
protected static ?string $slug = 'master/users';
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@example.com')
->autocomplete(false)
->required()
->maxLength(254)
->email()
->unique(ignoreRecord: true),
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')
->required()
->relationship('roles', 'name', function (Builder $query): Builder {
return $query->whereNot('name', RoleEnum::DEVELOPER);
})
->multiple()
->preload()
->searchable(),
Hidden::make('password')
->default(fn (): string => config('auth.password_default'))
->visibleOn('create'),
])
->columns(1);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')
->label('Nama')
->searchable()
->sortable(),
TextColumn::make('email')
->label('Alamat Surel')
->searchable()
->sortable(),
TextColumn::make('username')
->label('Nama Pengguna')
->searchable()
->sortable(),
TextColumn::make('roles.name')
->label('Peran')
->searchable()
->sortable()
->badge()
->getStateUsing(fn (User $record): array => $record->roles->pluck('name', 'id')->toArray()),
...TimestampColumns::make(),
])
->filters([
TrashedFilter::make()
->native(false)
->visible(fn () => auth()->user()?->hasRole(RoleEnum::DEVELOPER->value)),
])
->recordActions([
EditAction::make()
->modalWidth(Width::Large),
DeleteAction::make(),
ForceDeleteAction::make(),
RestoreAction::make(),
ChangePasswordAction::make('changePassword'),
])
->toolbarActions([
BulkActionGroup::make([
...DefaultBulkActions::make('Pengguna'),
]),
])
->emptyStateIcon(Heroicon::UserGroup)
->emptyStateDescription('Setelah Anda membubat data 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

@ -2,14 +2,18 @@
namespace App\Models;
use App\Enums\RoleEnum;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
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
{
use HasFactory, Notifiable, SoftDeletes;
use HasFactory, HasRoles, Notifiable, SoftDeletes;
protected $guarded = ['id'];
@ -23,4 +27,12 @@ protected function casts(): array
'password' => 'hashed',
];
}
#[Scope]
protected function withoutDeveloper(Builder $query): void
{
$query->whereDoesntHave('roles', function ($q) {
$q->where('name', RoleEnum::DEVELOPER);
});
}
}

View File

@ -3,6 +3,7 @@
namespace App\Providers\Filament;
use App\Filament\Pages\Auth\Login;
use BezhanSalleh\FilamentShield\FilamentShieldPlugin;
use DiogoGPinto\AuthUIEnhancer\AuthUIEnhancerPlugin;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
@ -59,6 +60,10 @@ public function panel(Panel $panel): Panel
Authenticate::class,
])
->plugins([
FilamentShieldPlugin::make()
->navigationSort(999)
->globallySearchable(false),
AuthUIEnhancerPlugin::make()
->formPanelPosition('left'),
]);

View File

@ -7,6 +7,7 @@
"license": "MIT",
"require": {
"php": "^8.2",
"bezhansalleh/filament-shield": "^4.1",
"diogogpinto/filament-auth-ui-enhancer": "^2.0",
"filament/filament": "^4.0",
"laravel/framework": "^12.0",

258
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": "28d56c0579aa0bff54a3eda86204b137",
"content-hash": "d3efc2f623e80c6e682768ab50e46f11",
"packages": [
{
"name": "anourvalar/eloquent-serialize",
@ -72,6 +72,179 @@
},
"time": "2025-12-04T13:38:21+00:00"
},
{
"name": "bezhansalleh/filament-plugin-essentials",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/bezhanSalleh/filament-plugin-essentials.git",
"reference": "3bfdb276a8993ccd5acd9d6b43fd4763cf221d3a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/bezhanSalleh/filament-plugin-essentials/zipball/3bfdb276a8993ccd5acd9d6b43fd4763cf221d3a",
"reference": "3bfdb276a8993ccd5acd9d6b43fd4763cf221d3a",
"shasum": ""
},
"require": {
"filament/filament": "^4.0|^5.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.1.0"
},
"funding": [
{
"url": "https://github.com/bezhanSalleh",
"type": "github"
}
],
"time": "2026-01-19T19:23:25+00:00"
},
{
"name": "bezhansalleh/filament-shield",
"version": "4.1.0",
"source": {
"type": "git",
"url": "https://github.com/bezhanSalleh/filament-shield.git",
"reference": "bb5ac95b3c10f801e4c54bb289be8c055968726a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/bezhanSalleh/filament-shield/zipball/bb5ac95b3c10f801e4c54bb289be8c055968726a",
"reference": "bb5ac95b3c10f801e4c54bb289be8c055968726a",
"shasum": ""
},
"require": {
"bezhansalleh/filament-plugin-essentials": "^1.0",
"filament/filament": "^4.0|^5.0",
"illuminate/contracts": "^11.28|^12.0",
"illuminate/support": "^11.28|^12.0",
"php": "^8.2",
"spatie/laravel-package-tools": "^1.92",
"spatie/laravel-permission": "^6.0"
},
"require-dev": {
"larastan/larastan": "^3.8",
"laravel/pint": "^1.26",
"nunomaduro/collision": "^8.8",
"orchestra/testbench": "^10.8",
"pestphp/pest": "^3.8|^4.0",
"pestphp/pest-plugin-laravel": "^3.2|^4.0",
"pestphp/pest-plugin-livewire": "^3.0|^4.0",
"pestphp/pest-plugin-type-coverage": "^3.6|^4.0",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan": "^2.1",
"phpstan/phpstan-deprecation-rules": "^2.0",
"phpstan/phpstan-phpunit": "^2.0",
"phpunit/phpunit": "^11.5",
"rector/jack": "^0.4.0",
"rector/rector": "^2.2",
"spatie/laravel-ray": "^1.43"
},
"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.1.0"
},
"funding": [
{
"url": "https://github.com/bezhanSalleh",
"type": "github"
}
],
"time": "2026-01-19T19:28:46+00:00"
},
{
"name": "blade-ui-kit/blade-heroicons",
"version": "2.6.0",
@ -5342,6 +5515,89 @@
],
"time": "2025-07-17T15:46:43+00:00"
},
{
"name": "spatie/laravel-permission",
"version": "6.24.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-permission.git",
"reference": "76adb1fc8d07c16a0721c35c4cc330b7a12598d7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-permission/zipball/76adb1fc8d07c16a0721c35c4cc330b7a12598d7",
"reference": "76adb1fc8d07c16a0721c35c4cc330b7a12598d7",
"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.24.0"
},
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2025-12-13T21:45:21+00:00"
},
{
"name": "spatie/shiki-php",
"version": "2.3.2",

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

@ -0,0 +1,263 @@
<?php
declare(strict_types=1);
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.resource_permission_prefixes_labels',
],
/*
|--------------------------------------------------------------------------
| 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,226 @@
<?php
namespace Database\Seeders;
use BezhanSalleh\FilamentShield\Support\Utils;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\PermissionRegistrar;
class ShieldSeeder extends Seeder
{
public function run(): void
{
app()[PermissionRegistrar::class]->forgetCachedPermissions();
$tenants = '[]';
$users = '[]';
$userTenantPivot = '[]';
$rolesWithPermissions = <<<'JSON'
[
{
"name": "Developer",
"guard_name": "web",
"permissions" : []
},
{
"name": "Pemilik",
"guard_name": "web",
"permissions" : []
},
{
"name": "Administrator",
"guard_name": "web",
"permissions" : []
}
]
JSON;
$directPermissions = '[]';
// 1. Seed tenants first (if present)
if (! blank($tenants) && $tenants !== '[]') {
static::seedTenants($tenants);
}
// 2. Seed roles with permissions
static::makeRolesWithPermissions($rolesWithPermissions);
// 3. Seed direct permissions
static::makeDirectPermissions($directPermissions);
// 4. Seed users with their roles/permissions (if present)
if (! blank($users) && $users !== '[]') {
static::seedUsers($users);
}
// 5. Seed user-tenant pivot (if present)
if (! blank($userTenantPivot) && $userTenantPivot !== '[]') {
static::seedUserTenantPivot($userTenantPivot);
}
$this->command->info('Shield Seeding Completed.');
}
protected static function seedTenants(string $tenants): void
{
if (blank($tenantData = json_decode($tenants, true))) {
return;
}
$tenantModel = '';
if (blank($tenantModel)) {
return;
}
foreach ($tenantData as $tenant) {
$tenantModel::firstOrCreate(
['id' => $tenant['id']],
$tenant
);
}
}
protected static function seedUsers(string $users): void
{
if (blank($userData = json_decode($users, true))) {
return;
}
$userModel = 'App\Models\User';
$tenancyEnabled = false;
foreach ($userData as $data) {
// Extract role/permission data before creating user
$roles = $data['roles'] ?? [];
$permissions = $data['permissions'] ?? [];
$tenantRoles = $data['tenant_roles'] ?? [];
$tenantPermissions = $data['tenant_permissions'] ?? [];
unset($data['roles'], $data['permissions'], $data['tenant_roles'], $data['tenant_permissions']);
$user = $userModel::firstOrCreate(
['email' => $data['email']],
$data
);
// Handle tenancy mode - sync roles/permissions per tenant
if ($tenancyEnabled && (! empty($tenantRoles) || ! empty($tenantPermissions))) {
foreach ($tenantRoles as $tenantId => $roleNames) {
$contextId = $tenantId === '_global' ? null : $tenantId;
setPermissionsTeamId($contextId);
$user->syncRoles($roleNames);
}
foreach ($tenantPermissions as $tenantId => $permissionNames) {
$contextId = $tenantId === '_global' ? null : $tenantId;
setPermissionsTeamId($contextId);
$user->syncPermissions($permissionNames);
}
} else {
// Non-tenancy mode
if (! empty($roles)) {
$user->syncRoles($roles);
}
if (! empty($permissions)) {
$user->syncPermissions($permissions);
}
}
}
}
protected static function seedUserTenantPivot(string $pivot): void
{
if (blank($pivotData = json_decode($pivot, true))) {
return;
}
$pivotTable = '';
if (blank($pivotTable)) {
return;
}
foreach ($pivotData as $row) {
$uniqueKeys = [];
if (isset($row['user_id'])) {
$uniqueKeys['user_id'] = $row['user_id'];
}
$tenantForeignKey = 'team_id';
if (! blank($tenantForeignKey) && isset($row[$tenantForeignKey])) {
$uniqueKeys[$tenantForeignKey] = $row[$tenantForeignKey];
}
if (! empty($uniqueKeys)) {
DB::table($pivotTable)->updateOrInsert($uniqueKeys, $row);
}
}
}
protected static function makeRolesWithPermissions(string $rolesWithPermissions): void
{
if (blank($rolePlusPermissions = json_decode($rolesWithPermissions, true))) {
return;
}
/** @var \Illuminate\Database\Eloquent\Model $roleModel */
$roleModel = Utils::getRoleModel();
/** @var \Illuminate\Database\Eloquent\Model $permissionModel */
$permissionModel = Utils::getPermissionModel();
$tenancyEnabled = false;
$teamForeignKey = 'team_id';
foreach ($rolePlusPermissions as $rolePlusPermission) {
$tenantId = $rolePlusPermission[$teamForeignKey] ?? null;
// Set tenant context for role creation and permission sync
if ($tenancyEnabled) {
setPermissionsTeamId($tenantId);
}
$roleData = [
'name' => $rolePlusPermission['name'],
'guard_name' => $rolePlusPermission['guard_name'],
];
// Include tenant ID in role data (can be null for global roles)
if ($tenancyEnabled && ! blank($teamForeignKey)) {
$roleData[$teamForeignKey] = $tenantId;
}
$role = $roleModel::firstOrCreate($roleData);
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))) {
return;
}
/** @var \Illuminate\Database\Eloquent\Model $permissionModel */
$permissionModel = Utils::getPermissionModel();
foreach ($permissions as $permission) {
if ($permissionModel::whereName($permission['name'])->doesntExist()) {
$permissionModel::create([
'name' => $permission['name'],
'guard_name' => $permission['guard_name'],
]);
}
}
}
}

View File

@ -2,6 +2,7 @@
namespace Database\Seeders;
use App\Enums\RoleEnum;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
@ -20,6 +21,7 @@ public function run(): void
'username' => 'pangestu',
'password' => Hash::make(config('auth.password_default')),
]);
$developer->assignRole(RoleEnum::DEVELOPER);
// owner
$owner = User::create([
@ -28,6 +30,7 @@ public function run(): void
'username' => 'owner',
'password' => Hash::make(config('auth.password_default')),
]);
$owner->assignRole(RoleEnum::OWNER);
// admin
$administrator = User::create([
@ -36,5 +39,6 @@ public function run(): void
'username' => 'admin',
'password' => Hash::make(config('auth.password_default')),
]);
$administrator->assignRole(RoleEnum::ADMINISTRATOR);
}
}