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

Nova Permission Laravel Package

vyuldashev/nova-permission

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require vyuldashev/nova-permission
    

    Ensure spatie/laravel-permission is also installed (follow Spatie's installation guide).

  2. Register the Tool: Add \Vyuldashev\NovaPermission\NovaPermissionTool::make() to the tools() method in app/Providers/NovaServiceProvider.php.

  3. Configure Middleware: Add \Vyuldashev\NovaPermission\ForgetCachedPermissions::class to the middleware array in config/nova.php.

  4. Update User Resource: Modify app/Nova/User.php to include MorphToMany fields for roles and permissions:

    use Vyuldashev\NovaPermission\Fields\Permission;
    use Vyuldashev\NovaPermission\Fields\Role;
    
    public function fields(Request $request)
    {
        return [
            // ... other fields
            Role::make(__('Roles')),
            Permission::make(__('Permissions')),
        ];
    }
    
  5. Publish Assets (if needed): Run php artisan vendor:publish --provider="Vyuldashev\NovaPermission\NovaPermissionServiceProvider" to publish config or views.

First Use Case

  • Assign Roles/Permissions to Users: Navigate to the Users section in Nova. The new Roles and Permissions fields will appear as multi-select dropdowns. Select roles/permissions to assign them to a user.

Implementation Patterns

Core Workflows

  1. Role and Permission Management:

    • Use the Permissions and Roles tools in Nova to create, edit, and delete roles/permissions via a dedicated UI.
    • Example: Create a Admin role with create-post, edit-post, and delete-post permissions.
  2. User Assignment:

    • Assign roles/permissions to users directly from the User resource page.
    • Use the MorphToMany fields to bulk-assign or remove roles/permissions.
  3. Gate/Policy Integration:

    • Leverage Spatie’s gate() and can() methods in your application logic:
      if (auth()->user()->can('edit-post')) {
          // Allow action
      }
      
    • Use Nova’s built-in authorization to restrict tool visibility:
      NovaPermissionTool::make()->onlyOnRoles(['admin']);
      
  4. Customizing Fields:

    • Override default fields in your User resource:
      Role::make(__('Roles'))
          ->displayUsing(new CustomRoleDisplay())
          ->onlyOnDetail(),
      
  5. Syncing with Existing Data:

    • If migrating from another permission system, use Spatie’s syncRoles() or syncPermissions() methods:
      $user->syncRoles(['admin', 'editor']);
      

Integration Tips

  • Nova Tool Configuration: Customize tool appearance in NovaServiceProvider:

    NovaPermissionTool::make()
        ->title('Custom Permissions')
        ->icon('lock')
        ->onlyOnRoles(['super-admin']),
    
  • Localization: Publish the language file and translate labels:

    php artisan vendor:publish --tag=nova-permission-lang
    
  • Testing: Use Spatie’s testing helpers in PHPUnit:

    $user->givePermissionTo('edit-post');
    $this->assertTrue($user->can('edit-post'));
    
  • Performance: Cache permissions in production (enabled by default via ForgetCachedPermissions middleware). Clear cache when roles/permissions change:

    \Spatie\Permission\PermissionRegistrar::forgetCachedPermissions();
    

Gotchas and Tips

Pitfalls

  1. Middleware Order:

    • Ensure ForgetCachedPermissions is placed after nova.auth in config/nova.php to avoid permission cache issues:
      'middleware' => [
          \Laravel\Nova\Http\Middleware\Authenticate::class,
          \Laravel\Nova\Http\Middleware\Authorize::class,
          \Vyuldashev\NovaPermission\ForgetCachedPermissions::class, // <-- Correct position
      ],
      
  2. Field Conflicts:

    • If MorphToMany fields don’t appear, verify:
      • The User model uses HasRoles and HasPermissions traits from Spatie.
      • No naming collisions with existing Nova fields (e.g., roles vs. role).
  3. Permission Caching:

    • Aggressive caching can cause stale permissions. Clear cache manually if changes aren’t reflected:
      php artisan cache:clear
      
    • Disable caching in config/permission.php during development:
      'use_cache' => env('APP_ENV') !== 'local',
      
  4. Nova Resource Caching:

    • Nova caches resource views. Clear them after adding new fields:
      php artisan nova:cache-reset
      
  5. Role Hierarchy:

    • Spatie’s permission system doesn’t natively support role hierarchies (e.g., admin inherits editor permissions). Use middleware or policies to enforce this:
      if (auth()->user()->hasRole('admin')) {
          return true; // Admin has all editor permissions
      }
      

Debugging

  1. Permission Not Showing:

    • Check if the permission table exists and is populated:
      php artisan db:show
      
    • Verify the model_has_permissions and model_has_roles pivot tables exist.
  2. Field Not Rendering:

    • Inspect browser console for JavaScript errors. Ensure Nova’s assets are compiled:
      npm run dev
      
    • Check if the nova-permission tool is registered in NovaServiceProvider.
  3. Mass Assignment Issues:

    • Ensure roles and permissions are in the $fillable or $guarded arrays of the User model.

Extension Points

  1. Custom Fields:

    • Extend Role or Permission fields by creating a custom class:
      use Vyuldashev\NovaPermission\Fields\Role as BaseRole;
      
      class CustomRole extends BaseRole
      {
          public function __construct()
          {
              parent::__construct();
              $this->withMeta(['custom' => 'value']);
          }
      }
      
  2. Additional Tools:

    • Create custom Nova tools for permission-related actions (e.g., bulk role assignment):
      class BulkRoleTool extends Tool
      {
          public function index(Request $request)
          {
              // Logic to assign roles to multiple users
          }
      }
      
  3. API Extensions:

    • Use Nova’s API to interact with permissions programmatically:
      $user = User::find(1);
      $user->load('roles', 'permissions');
      return response()->json($user);
      
  4. Event Listeners:

    • Listen to Spatie’s events to trigger actions (e.g., log permission changes):
      \Spatie\Permission\Events\RoleDeleted::class => [
          \App\Listeners\LogPermissionChange::class,
      ],
      
  5. Policy Integration:

    • Create custom policies for fine-grained control:
      class PostPolicy
      {
          public function update(User $user, Post $post)
          {
              return $user->can('edit-post') && $post->user_id === $user->id;
          }
      }
      
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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky