first init
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'name' => 'Role',
|
||||
];
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Database\Seeders;
|
||||
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
class RoleDatabaseSeeder extends Seeder
|
||||
{
|
||||
/**
|
||||
* Run the database seeds.
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
// $this->call([]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Spatie\Permission\Models\Role as SpatieRole;
|
||||
|
||||
class Role extends SpatieRole
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $fillable = ['name', 'guard_name', 'fullname', 'context'];
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\BaseCrudController;
|
||||
use App\Services\ActivityLogger;
|
||||
use Exception;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Role\Entities\Role;
|
||||
use Modules\Role\Http\Requests\RoleRequest;
|
||||
use Modules\Role\Repositories\Contracts\RoleRepositoryInterface;
|
||||
use Modules\Role\Transformers\RoleResource;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class RoleController extends BaseCrudController
|
||||
{
|
||||
protected $modelClass = Role::class;
|
||||
|
||||
protected $resourceClass = RoleResource::class;
|
||||
|
||||
protected $requestClass = RoleRequest::class;
|
||||
|
||||
protected $resourceName = 'role';
|
||||
|
||||
protected $resourceNamePlural = 'roles';
|
||||
|
||||
public function __construct(RoleRepositoryInterface $repository)
|
||||
{
|
||||
parent::__construct($repository);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare data for store method
|
||||
*/
|
||||
protected function prepareStoreData(array $validated): array
|
||||
{
|
||||
return $validated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare data for update method
|
||||
*/
|
||||
protected function prepareUpdateData(array $validated, $role): array
|
||||
{
|
||||
return $validated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*/
|
||||
public function update(Request $request, string $id): JsonResponse
|
||||
{
|
||||
$this->authorize('update', $this->modelClass);
|
||||
|
||||
try {
|
||||
$item = $this->repository->findById($id);
|
||||
|
||||
if (! $item) {
|
||||
return $this->errorResponse($this->getNotFoundMessage(), 404);
|
||||
}
|
||||
|
||||
$validated = $this->validateRequest($request);
|
||||
$data = $this->prepareUpdateData($validated, $item);
|
||||
|
||||
// Use repository update method to handle permissions
|
||||
$updatedItem = $this->repository->update($id, $data);
|
||||
|
||||
ActivityLogger::log("Updated {$this->resourceName}: {$this->getItemName($updatedItem)}", $updatedItem);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => new $this->resourceClass($updatedItem),
|
||||
'message' => $this->getSuccessMessage('update'),
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
Log::error("Error updating {$this->resourceName}: ".$e->getMessage());
|
||||
|
||||
return $this->errorResponse($this->getErrorMessage('update').': '.$e->getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check dependencies before deletion
|
||||
*/
|
||||
protected function checkDependencies($role): ?JsonResponse
|
||||
{
|
||||
// Check if role has users assigned
|
||||
if ($role->users()->count() > 0) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Cannot delete role. It has users assigned to it.',
|
||||
], 422);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all permissions for role assignment
|
||||
*/
|
||||
public function permissions(): JsonResponse
|
||||
{
|
||||
$permissions = Permission::all();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $permissions->map(function ($permission) {
|
||||
return [
|
||||
'id' => $permission->id,
|
||||
'name' => $permission->name,
|
||||
'guard_name' => $permission->guard_name,
|
||||
'route_name' => $permission->route_name,
|
||||
];
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign permissions to a role
|
||||
*/
|
||||
public function assignPermissions(Request $request, string $id): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'permissions' => 'required|array',
|
||||
'permissions.*' => ['required', 'uuid', Rule::exists('permissions', 'id')],
|
||||
]);
|
||||
|
||||
$role = $this->repository->find($id);
|
||||
$this->repository->syncPermissions($role, $request->permissions);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Permissions assigned successfully.',
|
||||
'data' => new RoleResource($role->load('permissions')),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get role with permissions
|
||||
*/
|
||||
public function show(string $id): JsonResponse
|
||||
{
|
||||
$role = $this->repository->find($id);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => new RoleResource($role->load('permissions')),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all roles with permissions
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$search = $request->get('search', '');
|
||||
$roles = $this->repository->withPermissions($search);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => RoleResource::collection($roles),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Public endpoint for registration form (no auth required)
|
||||
*/
|
||||
public function publicRole(): JsonResponse
|
||||
{
|
||||
$roles = $this->repository->all();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => RoleResource::collection($roles),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Role\Entities\Role;
|
||||
|
||||
class RoleRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255'
|
||||
],
|
||||
'guard_name' => [
|
||||
'required',
|
||||
'string',
|
||||
'in:api,web'
|
||||
],
|
||||
'permissions' => [
|
||||
'sometimes',
|
||||
'array'
|
||||
],
|
||||
'permissions.*' => [
|
||||
'required',
|
||||
'uuid',
|
||||
Rule::exists('permissions', 'id'),
|
||||
],
|
||||
'fullname' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
],
|
||||
'context' => [
|
||||
'required',
|
||||
'string',
|
||||
Rule::in(['member', 'admin']),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the validator instance.
|
||||
*/
|
||||
public function withValidator($validator)
|
||||
{
|
||||
$validator->after(function ($validator) {
|
||||
$roleId = $this->route('role');
|
||||
$name = $this->input('name');
|
||||
$guardName = $this->input('guard_name', 'api');
|
||||
|
||||
// Check for unique name within the same guard
|
||||
$query = Role::where('name', $name)
|
||||
->where('guard_name', $guardName);
|
||||
|
||||
if ($roleId) {
|
||||
$query->where('id', '!=', $roleId);
|
||||
}
|
||||
|
||||
if ($query->exists()) {
|
||||
$validator->errors()->add('name', 'This role name already exists for the selected guard.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get custom messages for validator errors.
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'name.required' => 'Role name is required.',
|
||||
'name.unique' => 'This role name already exists for the selected guard.',
|
||||
'guard_name.required' => 'Guard name is required.',
|
||||
'guard_name.in' => 'Guard name must be either api or web.',
|
||||
'permissions.array' => 'Permissions must be an array.',
|
||||
'permissions.*.uuid' => 'Each permission id must be a valid UUID.',
|
||||
'permissions.*.exists' => 'One or more selected permissions do not exist.',
|
||||
'fullname.required' => 'Fullname is required.',
|
||||
'fullname.string' => 'Fullname must be a string.',
|
||||
'fullname.max' => 'Fullname must be less than 255 characters.',
|
||||
'context.required' => 'Konteks peranan diperlukan.',
|
||||
'context.in' => 'Konteks peranan mestilah ahli atau pentadbir.',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Policies;
|
||||
|
||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||
use Modules\Role\Entities\Role;
|
||||
|
||||
class RolePolicy
|
||||
{
|
||||
use HandlesAuthorization;
|
||||
|
||||
/**
|
||||
* Determine whether the user can view any models.
|
||||
*/
|
||||
public function viewAny($user): bool
|
||||
{
|
||||
return $user->hasPermissionTo('lihat jenis pengguna');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can view the model.
|
||||
*/
|
||||
public function view($user, ?Role $role = null): bool
|
||||
{
|
||||
return $user->hasPermissionTo('lihat jenis pengguna');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can create models.
|
||||
*/
|
||||
public function create($user): bool
|
||||
{
|
||||
return $user->hasPermissionTo('tambah jenis pengguna');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can update the model.
|
||||
*/
|
||||
public function update($user, ?Role $role = null): bool
|
||||
{
|
||||
return $user->hasPermissionTo('kemaskini jenis pengguna');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can delete any model.
|
||||
*/
|
||||
public function deleteAny($user): bool
|
||||
{
|
||||
return $user->hasPermissionTo('hapus jenis pengguna');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can delete the model.
|
||||
*/
|
||||
public function delete($user, ?Role $role = null): bool
|
||||
{
|
||||
return $user->hasPermissionTo('hapus jenis pengguna');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Providers;
|
||||
|
||||
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
|
||||
|
||||
class EventServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The event handler mappings for the application.
|
||||
*
|
||||
* @var array<string, array<int, string>>
|
||||
*/
|
||||
protected $listen = [];
|
||||
|
||||
/**
|
||||
* Indicates if events should be discovered.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected static $shouldDiscoverEvents = true;
|
||||
|
||||
/**
|
||||
* Configure the proper event listeners for email verification.
|
||||
*/
|
||||
protected function configureEmailVerification(): void {}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Nwidart\Modules\Traits\PathNamespace;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
|
||||
class RoleServiceProvider extends ServiceProvider
|
||||
{
|
||||
use PathNamespace;
|
||||
|
||||
protected string $name = 'Role';
|
||||
|
||||
protected string $nameLower = 'role';
|
||||
|
||||
/**
|
||||
* Boot the application events.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
$this->registerCommands();
|
||||
$this->registerCommandSchedules();
|
||||
$this->registerTranslations();
|
||||
$this->registerConfig();
|
||||
$this->registerViews();
|
||||
$this->loadMigrationsFrom(module_path($this->name, 'Database/Migrations'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the service provider.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->register(EventServiceProvider::class);
|
||||
$this->app->register(RouteServiceProvider::class);
|
||||
|
||||
// Register repository binding
|
||||
$this->app->bind(
|
||||
\Modules\Role\Repositories\Contracts\RoleRepositoryInterface::class,
|
||||
\Modules\Role\Repositories\RoleRepository::class
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register commands in the format of Command::class
|
||||
*/
|
||||
protected function registerCommands(): void
|
||||
{
|
||||
// $this->commands([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register command Schedules.
|
||||
*/
|
||||
protected function registerCommandSchedules(): void
|
||||
{
|
||||
// $this->app->booted(function () {
|
||||
// $schedule = $this->app->make(Schedule::class);
|
||||
// $schedule->command('inspire')->hourly();
|
||||
// });
|
||||
}
|
||||
|
||||
/**
|
||||
* Register translations.
|
||||
*/
|
||||
public function registerTranslations(): void
|
||||
{
|
||||
$langPath = resource_path('lang/modules/'.$this->nameLower);
|
||||
|
||||
if (is_dir($langPath)) {
|
||||
$this->loadTranslationsFrom($langPath, $this->nameLower);
|
||||
$this->loadJsonTranslationsFrom($langPath);
|
||||
} else {
|
||||
$this->loadTranslationsFrom(module_path($this->name, 'Lang'), $this->nameLower);
|
||||
$this->loadJsonTranslationsFrom(module_path($this->name, 'Lang'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register config.
|
||||
*/
|
||||
protected function registerConfig(): void
|
||||
{
|
||||
$configPath = module_path($this->name, config('modules.paths.generator.config.path'));
|
||||
|
||||
if (is_dir($configPath)) {
|
||||
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configPath));
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isFile() && $file->getExtension() === 'php') {
|
||||
$config = str_replace($configPath.DIRECTORY_SEPARATOR, '', $file->getPathname());
|
||||
$config_key = str_replace([DIRECTORY_SEPARATOR, '.php'], ['.', ''], $config);
|
||||
$segments = explode('.', $this->nameLower.'.'.$config_key);
|
||||
|
||||
// Remove duplicated adjacent segments
|
||||
$normalized = [];
|
||||
foreach ($segments as $segment) {
|
||||
if (end($normalized) !== $segment) {
|
||||
$normalized[] = $segment;
|
||||
}
|
||||
}
|
||||
|
||||
$key = ($config === 'config.php') ? $this->nameLower : implode('.', $normalized);
|
||||
|
||||
$this->publishes([$file->getPathname() => config_path($config)], 'config');
|
||||
$this->merge_config_from($file->getPathname(), $key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge config from the given path recursively.
|
||||
*/
|
||||
protected function merge_config_from(string $path, string $key): void
|
||||
{
|
||||
$existing = config($key, []);
|
||||
$module_config = require $path;
|
||||
|
||||
config([$key => array_replace_recursive($existing, $module_config)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register views.
|
||||
*/
|
||||
public function registerViews(): void
|
||||
{
|
||||
$viewPath = resource_path('views/modules/'.$this->nameLower);
|
||||
$sourcePath = module_path($this->name, 'Resources/Views');
|
||||
|
||||
$this->publishes([$sourcePath => $viewPath], ['views', $this->nameLower.'-module-views']);
|
||||
|
||||
$this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);
|
||||
|
||||
Blade::componentNamespace(config('modules.namespace').'\\' . $this->name . '\\View\\Components', $this->nameLower);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the services provided by the provider.
|
||||
*/
|
||||
public function provides(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
private function getPublishableViewPaths(): array
|
||||
{
|
||||
$paths = [];
|
||||
foreach (config('view.paths') as $path) {
|
||||
if (is_dir($path.'/modules/'.$this->nameLower)) {
|
||||
$paths[] = $path.'/modules/'.$this->nameLower;
|
||||
}
|
||||
}
|
||||
|
||||
return $paths;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Providers;
|
||||
|
||||
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
class RouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
protected string $name = 'Role';
|
||||
|
||||
/**
|
||||
* Called before routes are registered.
|
||||
*
|
||||
* Register any model bindings or pattern based filters.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
parent::boot();
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the routes for the application.
|
||||
*/
|
||||
public function map(): void
|
||||
{
|
||||
$this->mapApiRoutes();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the "web" routes for the application.
|
||||
*
|
||||
* These routes all receive session state, CSRF protection, etc.
|
||||
*/
|
||||
protected function mapWebRoutes(): void
|
||||
{
|
||||
Route::middleware('web')->group(module_path($this->name, '/Routes/web.php'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the "api" routes for the application.
|
||||
*
|
||||
* These routes are typically stateless.
|
||||
*/
|
||||
protected function mapApiRoutes(): void
|
||||
{
|
||||
Route::middleware('api')->name('api.')->group(module_path($this->name, '/Routes/api.php'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Repositories\Contracts;
|
||||
|
||||
use Modules\Role\Entities\Role;
|
||||
|
||||
interface RoleRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* Get all roles
|
||||
*/
|
||||
public function all();
|
||||
|
||||
/**
|
||||
* Find role by ID
|
||||
*/
|
||||
public function find($id);
|
||||
|
||||
/**
|
||||
* Find role by ID (alias for find)
|
||||
*/
|
||||
public function findById($id);
|
||||
|
||||
/**
|
||||
* Create a new role
|
||||
*/
|
||||
public function create(array $data);
|
||||
|
||||
/**
|
||||
* Update role
|
||||
*/
|
||||
public function update($id, array $data);
|
||||
|
||||
/**
|
||||
* Delete role
|
||||
*/
|
||||
public function delete($id);
|
||||
|
||||
/**
|
||||
* Get roles with permissions
|
||||
*/
|
||||
public function withPermissions($search = '');
|
||||
|
||||
/**
|
||||
* Sync permissions for a role
|
||||
*/
|
||||
public function syncPermissions(Role $role, array $permissionIds);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Repositories;
|
||||
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Role\Entities\Role;
|
||||
use Modules\Role\Repositories\Contracts\RoleRepositoryInterface;
|
||||
|
||||
class RoleRepository implements RoleRepositoryInterface
|
||||
{
|
||||
protected $model;
|
||||
|
||||
public function __construct(Role $model)
|
||||
{
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all roles
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
return $this->model->where('name', '!=', 'DEVELOPER')->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find role by ID
|
||||
*/
|
||||
public function find($id)
|
||||
{
|
||||
return $this->model->findOrFail($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find role by ID (alias for find)
|
||||
*/
|
||||
public function findById($id)
|
||||
{
|
||||
return $this->find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new role
|
||||
*/
|
||||
public function create(array $data)
|
||||
{
|
||||
return DB::transaction(function () use ($data) {
|
||||
$role = $this->model->create([
|
||||
'name' => $data['name'],
|
||||
'guard_name' => $data['guard_name'] ?? 'api',
|
||||
'fullname' => $data['fullname'] ?? null,
|
||||
'context' => $data['context'] ?? 'member',
|
||||
]);
|
||||
|
||||
if (isset($data['permissions']) && is_array($data['permissions'])) {
|
||||
$this->syncPermissions($role, $data['permissions']);
|
||||
}
|
||||
|
||||
return $role->load('permissions');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update role
|
||||
*/
|
||||
public function update($id, array $data)
|
||||
{
|
||||
return DB::transaction(function () use ($id, $data) {
|
||||
$role = $this->find($id);
|
||||
|
||||
$role->update([
|
||||
'name' => $data['name'],
|
||||
'guard_name' => $data['guard_name'] ?? $role->guard_name,
|
||||
'fullname' => $data['fullname'] ?? $role->fullname,
|
||||
'context' => $data['context'] ?? $role->context ?? 'member',
|
||||
]);
|
||||
|
||||
if (isset($data['permissions']) && is_array($data['permissions'])) {
|
||||
$this->syncPermissions($role, $data['permissions']);
|
||||
}
|
||||
|
||||
return $role->load('permissions');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete role
|
||||
*/
|
||||
public function delete($id)
|
||||
{
|
||||
$role = $this->find($id);
|
||||
return $role->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get roles with permissions
|
||||
*/
|
||||
public function withPermissions($search = '')
|
||||
{
|
||||
$query = $this->model->with('permissions')
|
||||
->where('name', '!=', 'DEVELOPER');
|
||||
|
||||
if (!empty($search)) {
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('name', 'ILIKE', "%{$search}%")
|
||||
->orWhere('fullname', 'ILIKE', "%{$search}%")
|
||||
->orWhere('guard_name', 'ILIKE', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
return $query->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync permissions for a role
|
||||
*/
|
||||
public function syncPermissions(Role $role, array $permissionIds)
|
||||
{
|
||||
$permissionIds = array_map(fn ($id) => (string) $id, $permissionIds);
|
||||
|
||||
$permissions = Permission::whereIn('id', $permissionIds)->get();
|
||||
|
||||
if ($permissions->count() !== count($permissionIds)) {
|
||||
throw new \InvalidArgumentException('One or more selected permissions do not exist.');
|
||||
}
|
||||
|
||||
$role->syncPermissions($permissions);
|
||||
|
||||
return $role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Role\Http\Controllers\RoleController;
|
||||
|
||||
// Public route for registration form (no auth required)
|
||||
Route::prefix('v1')->group(function () {
|
||||
Route::get('public/roles', [RoleController::class, 'publicRole']);
|
||||
});
|
||||
|
||||
// Protected routes (auth required)
|
||||
Route::middleware(['auth:sanctum'])->prefix('v1')->group(function () {
|
||||
Route::apiResource('roles', RoleController::class)->names('role');
|
||||
|
||||
// Permission management routes
|
||||
Route::get('permissions', [RoleController::class, 'permissions'])->name('permissions.index');
|
||||
Route::post('roles/{role}/permissions', [RoleController::class, 'assignPermissions'])->name('roles.permissions.assign');
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Role\Transformers;
|
||||
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class RoleResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*/
|
||||
public function toArray($request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'guard_name' => $this->guard_name,
|
||||
'fullname' => $this->fullname,
|
||||
'context' => $this->context ?? 'member',
|
||||
'permissions' => $this->whenLoaded('permissions', function () {
|
||||
return $this->permissions->map(function ($permission) {
|
||||
return [
|
||||
'id' => $permission->id,
|
||||
'name' => $permission->name,
|
||||
'guard_name' => $permission->guard_name,
|
||||
'route_name' => $permission->route_name,
|
||||
];
|
||||
});
|
||||
}),
|
||||
'created_at' => $this->created_at?->toISOString(),
|
||||
'updated_at' => $this->updated_at?->toISOString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "nwidart/role",
|
||||
"description": "",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Nicolas Widart",
|
||||
"email": "n.widart@gmail.com"
|
||||
}
|
||||
],
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [],
|
||||
"aliases": {
|
||||
|
||||
}
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Modules\\Role\\": "App",
|
||||
"Modules\\Role\\Database\\Factories\\": "database/factories/",
|
||||
"Modules\\Role\\Database\\Seeders\\": "database/seeders/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Modules\\Role\\Tests\\": "tests/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "Role",
|
||||
"alias": "role",
|
||||
"description": "",
|
||||
"keywords": [],
|
||||
"priority": 0,
|
||||
"providers": [
|
||||
"Modules\\Role\\Providers\\RoleServiceProvider"
|
||||
],
|
||||
"files": []
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"axios": "^1.1.2",
|
||||
"laravel-vite-plugin": "^0.7.5",
|
||||
"sass": "^1.69.5",
|
||||
"postcss": "^8.3.7",
|
||||
"vite": "^4.0.0"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user