Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Userpermission Laravel Package

ilbeygi/userpermission

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ilbeygi/userpermission:"dev-master"
    
    • Use dev-master only if actively maintained; prefer a stable version if available.
  2. Register Provider: Add to config/app.php:

    'providers' => [
        Ilbeygi\UserPermission\UserPermissionServiceProvider::class,
    ],
    
  3. Publish Config & Migrate:

    php artisan vendor:publish --tag=userPermissionPackage_ilbeygi_ir
    php artisan migrate
    
  4. Add Middleware: Register in app/Http/Kernel.php:

    'routeMiddleware' => [
        'checkRoles' => \Ilbeygi\UserPermission\Middlewares\CheckRole::class,
    ],
    
  5. Seed Routes (One-Time):

    • Visit /saveAllRouteNameInDatabase (requires login).
    • Remove the route from vendor/ilbeygi/userpermission/src/route.php afterward.
  6. Access Panel: Navigate to /panel/permissions to manage roles/permissions.

First Use Case

Assign a role to a user and restrict access:

// Assign 'admin' role to a user
$user->assignRole('admin');

// Protect a route
Route::get('/admin/dashboard', function () {
    return view('admin.dashboard');
})->middleware('checkRoles:admin');

Implementation Patterns

Role Assignment Workflows

  1. Assign Roles to Users:

    // Single role
    $user->assignRole('editor');
    
    // Multiple roles
    $user->assignRole(['editor', 'moderator']);
    
  2. Check Role Permissions:

    // Check if user has role
    if ($user->hasRole('admin')) {
        // Grant access
    }
    
    // Check if user has any of multiple roles
    if ($user->hasAnyRole(['admin', 'editor'])) {
        // Grant access
    }
    
  3. Dynamic Role-Based Middleware:

    // In routes
    Route::get('/profile', function () {
        return view('profile');
    })->middleware('checkRoles:user,editor');
    
    // Or in controller constructor
    public function __construct() {
        $this->middleware('checkRoles:admin')->only(['destroy']);
    }
    

Permission Management

  1. Define Custom Permissions: Extend the package by adding permissions to the permissions table:

    DB::table('permissions')->insert([
        ['name' => 'delete_posts', 'description' => 'Delete user posts'],
        ['name' => 'manage_users', 'description' => 'CRUD users'],
    ]);
    
  2. Assign Permissions to Roles: Use the /panel/permissions UI or manually:

    $role = Role::findByName('admin');
    $role->attachPermission('delete_posts');
    
  3. Gate Integration:

    Gate::define('delete-post', function ($user) {
        return $user->hasPermission('delete_posts');
    });
    

Integration Tips

  • Laravel Nova/Panel: Use the /panel/permissions UI for non-developers to manage roles/permissions.
  • API Routes: Apply middleware to API routes:
    Route::middleware('api', 'checkRoles:admin')->group(function () {
        Route::get('/api/admin', function () { ... });
    });
    
  • Seeding Roles: Seed initial roles in DatabaseSeeder:
    $roles = ['admin', 'editor', 'user'];
    foreach ($roles as $role) {
        Role::create(['name' => $role]);
    }
    

Gotchas and Tips

Pitfalls

  1. Route Caching:

    • After adding new routes, re-run /saveAllRouteNameInDatabase to update the database.
    • Warning: Deleting the route from vendor/ is permanent; ensure you’ve backed up custom routes.
  2. Middleware Misconfiguration:

    • Forgetting to register checkRoles in Kernel.php will silently fail.
    • Fix: Verify the middleware exists in $routeMiddleware.
  3. Permission Overrides:

    • Custom permissions in the permissions table won’t auto-sync with the UI.
    • Solution: Manually add them via the panel or seed them during migration.
  4. Role Hierarchy:

    • The package doesn’t enforce role hierarchies (e.g., admin > editor).
    • Workaround: Implement logic in middleware or gates:
      if ($user->hasRole('admin') || ($user->hasRole('editor') && $request->isMethod('get'))) {
          // Allow
      }
      

Debugging

  1. Check Route Permissions: Run:

    php artisan route:list
    
    • Ensure routes are stored in the route_permissions table.
  2. Log Middleware Errors: Add to app/Exceptions/Handler.php:

    report(function (CheckRoleException $e) {
        Log::error('Role check failed: ' . $e->getMessage());
    });
    
  3. UI Panel Issues:

    • Clear cache if the panel loads blank:
      php artisan view:clear
      php artisan cache:clear
      

Extension Points

  1. Custom Role Models: Extend the Role model:

    class CustomRole extends \Ilbeygi\UserPermission\Models\Role
    {
        public function customMethod() { ... }
    }
    
    • Bind in UserPermissionServiceProvider:
      $this->app->bind(\Ilbeygi\UserPermission\Models\Role::class, CustomRole::class);
      
  2. Override Permission Logic: Publish and modify the config:

    php artisan vendor:publish --tag=userPermissionPackage_ilbeygi_ir --force
    
    • Edit config/userpermission.php to change default behaviors (e.g., permission caching).
  3. Add Custom Fields: Extend migrations:

    Schema::table('roles', function (Blueprint $table) {
        $table->string('custom_field')->nullable();
    });
    
    • Update the Role model and panel views accordingly.

Performance Tips

  1. Cache Role Checks: Add to User model:

    public function getRolesAttribute()
    {
        return cache()->remember("user.roles.{$this->id}", now()->addHours(1), function () {
            return $this->roles->pluck('name');
        });
    }
    
  2. Eager Load Roles: Avoid N+1 queries:

    $users = User::with('roles')->get();
    
  3. Batch Assign Roles: For bulk operations:

    $users->each(function ($user) {
        $user->assignRole('user');
    });
    
    • Use transactions for large datasets:
      DB::transaction(function () use ($users) {
          $users->each(...);
      });
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle