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

Permissions Laravel Package

beartropy/permissions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require beartropy/permissions
    

    Publish the package assets and config:

    php artisan vendor:publish --provider="Beartropy\Permissions\PermissionsServiceProvider"
    
  2. Run Migrations:

    php artisan migrate
    

    (Ensure spatie/laravel-permission migrations have run first.)

  3. Register Routes: Add the middleware and routes to routes/web.php:

    Route::middleware(['auth', 'verified'])->group(function () {
        require __DIR__ . '/permissions.php';
    });
    
  4. First Use Case: Visit /permissions (or your configured route) to access the dashboard. Authenticate as an admin to manage roles/permissions.


Implementation Patterns

Core Workflows

  1. Role Management:

    • Create: Navigate to "Roles" → "+ New Role" → Define name, guard, and permissions.
    • Bulk Assign: Use the checkbox selector to assign multiple permissions to a role at once.
    • Hierarchy: Drag-and-drop roles to set parent-child relationships (if using Spatie’s role hierarchy).
  2. Permission Management:

    • Grouping: Organize permissions into logical groups (e.g., posts.*, users.*) via the "Permission Groups" tab.
    • Model-Based Permissions: Leverage Spatie’s Permission::findOrCreate() in your models to auto-generate permissions (e.g., Post::class . '.edit').
  3. User Assignment:

    • Bulk Actions: Select users in the "Users" tab and assign/detach roles via dropdown menus.
    • API Integration: Use the underlying Spatie API for programmatic assignments:
      $user->givePermissionTo('edit-posts');
      $user->assignRole('editor');
      

Integration Tips

  • Livewire Components: The UI is built with Livewire. Extend functionality by creating custom Livewire components that interact with the package’s models (Role, Permission, User). Example:

    use Beartropy\Permissions\Models\Role;
    use Livewire\Component;
    
    class CustomRoleManager extends Component {
        public function syncPermissions($roleId, $permissionIds) {
            $role = Role::findOrFail($roleId);
            $role->syncPermissions($permissionIds);
        }
    }
    
  • Blade Directives: Use Spatie’s directives in your views for conditional rendering:

    @can('edit-posts')
        <button>Edit Post</button>
    @endcan
    
  • API Endpoints: Expose the UI’s functionality via API routes for headless applications:

    Route::get('/api/permissions/roles', [RoleController::class, 'index']);
    

Gotchas and Tips

Pitfalls

  1. Missing Spatie Dependency:

    • Error: Class 'Spatie\Permission\Permission' not found.
    • Fix: Ensure spatie/laravel-permission is installed and configured before using this package.
  2. Guard Mismatch:

    • Error: Roles/permissions not appearing for users.
    • Fix: Verify the guard name in the UI matches your Auth::guard() configuration (default: web).
  3. Livewire Caching:

    • Issue: UI updates lag or fail silently.
    • Fix: Clear Livewire cache:
      php artisan cache:clear
      php artisan view:clear
      
  4. Permission Groups:

    • Gotcha: The UI groups permissions by prefix (e.g., posts.*), but Spatie’s Permission::create() requires exact names.
    • Tip: Use the "Permission Groups" tab to visualize and manage groups before creating them programmatically.

Debugging

  • Log Permissions: Dump permissions for a role/user to debug:

    dd(auth()->user()->getAllPermissions());
    dd(\App\Models\Role::find(1)->permissions);
    
  • Check Middleware: Ensure your admin routes use the correct middleware (e.g., auth, verified, and optionally can:admin).

Extension Points

  1. Custom Fields: Extend the Role or Permission models to add custom attributes (e.g., description, priority):

    use Beartropy\Permissions\Models\Role as BaseRole;
    
    class Role extends BaseRole {
        protected $casts = [
            'description' => 'string',
        ];
    }
    

    Update the UI via Livewire property binding.

  2. Theming: Override the package’s Tailwind CSS by publishing the assets:

    php artisan vendor:publish --tag=permissions-assets
    

    Modify resources/css/permissions.css.

  3. Audit Logging: Integrate with spatie/laravel-activitylog to track role/permission changes:

    use Spatie\Activitylog\LogOptions;
    
    $role->logActivity('updated', $options = new LogOptions());
    
  4. Multi-Guard Support: Configure multiple guards in config/auth.php and extend the UI to toggle between them (requires custom Livewire logic).

Pro Tips

  • Seed Data: Use Laravel’s seeder to pre-populate roles/permissions:

    use Beartropy\Permissions\Models\Role;
    use Beartropy\Permissions\Models\Permission;
    
    public function run() {
        $admin = Role::create(['name' => 'admin', 'guard_name' => 'web']);
        Permission::create(['name' => 'access-admin', 'guard_name' => 'web']);
        $admin->givePermissionTo('access-admin');
    }
    
  • Soft Deletes: Enable soft deletes for roles/permissions in the PermissionsServiceProvider:

    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class Role extends Model {
        use SoftDeletes;
    }
    
  • Performance: For large-scale applications, eager-load relationships in the UI:

    $roles = Role::with('permissions', 'users')->get();
    
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