Download the PHP package creativecrafts/laravel-role-permission-manager without Composer
On this page you can find all versions of the php package creativecrafts/laravel-role-permission-manager. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download creativecrafts/laravel-role-permission-manager
More information about creativecrafts/laravel-role-permission-manager
Files in creativecrafts/laravel-role-permission-manager
Package laravel-role-permission-manager
Short Description A simple package to manager an application role and permissions.
License MIT
Homepage https://github.com/CreativeCrafts/laravel-role-permission-manager
Informations about the package laravel-role-permission-manager
Laravel Role Permission Manager
Laravel Role Permission Manager is a powerful yet simple package designed to streamline the management of roles and permissions in Laravel applications. It provides an intuitive interface for creating, assigning, and managing user roles and their associated permissions, allowing developers to implement complex authorization systems with ease.
This package is perfect for applications of all sizes, from small projects to large-scale enterprise systems, offering flexibility and scalability in handling user access control. Whether you're building a simple blog with admin roles or a complex multi-tenant application with granular permissions, Laravel Role Permission Manager has got you covered.
Features
- Easy integration with Laravel's authentication system
- Flexible role and permission management
- Middleware for protecting routes based on roles and permissions
- Blade directives for easy view-level access control
- Easily extendable and customizable
- Comprehensive testing suite ensuring reliability
- Clear and concise API for programmatic access control
Table of Contents
- Getting Started
- Installation
- Configuration
- Database Migrations
- Usage
- Models
- Permission Model
- Role Model
- Middleware
- HandleInertiaRequests Middleware
- Key Features
- How it Works
- Usage
- Accessing Permissions in the Frontend
- PermissionMiddleware
- Key Features
- Usage
- Multiple Permissions
- Handling Unauthorized Access
- RoleMiddleware
- Key Features
- Usage
- Multiple Roles
- Handling Unauthorized Access
- HandleInertiaRequests Middleware
- Facade
- Artisan Commands
- Automatic Route Registration
- Customizing Route Registration
- Models
- Authorization Policies
- Policy Registration
- Using the Policies
- Available Policy Methods
- Custom Policies
- Frontend Integration
- Accessing Permissions in the Frontend
- Vue Permission Helper Functions
- Key Functions
- Usage in Vue Components
- Note on Permissions Data
- React Permission Hooks
- Key Features
- Usage
- Available Functions
- Note on Permissions Data
- Contributing
- Security
- Credits
- License
Getting Started
Installation
-
Install the package via Composer:
-
Publish and run the migrations:
- Optionally, publish the config file:
Publishing TypeScript Files
To use the TypeScript helper files in your application, you can publish them using the following command:
Configuration
Customize the package behavior by editing the published config file config/role-permission-manager.php.
Key configuration options:
- user_model: Specify the User model used by your application
- roles_table: Define the name for the roles table
- permissions_table: Define the name for the permissions table
- cache_expiration_time: Set the cache expiration time for roles and permissions
- default_guard: Specify the default guard for role and permission checks
- use_package_routes: If set to true, the package will register its routes automatically.
- route_middleware: Define the middleware to be applied to the package routes
- route_prefix: Set the prefix for the package routes
- super_admin_role: Define the role that should be considered as a super admin
- auto_create_permissions: Enable or disable automatic creation of permissions
- enable_wildcard_permission: Enable or disable wildcard permissions
- case_sensitive_permissions: Choose whether permission names should be case-sensitive
Registering Your User Model
After installing the package, you need to register your User model. This step is crucial for the package to work correctly with your application's user model.
Add the following code to your AppServiceProvider
or a custom service provider:
Database Migrations
The package includes migrations for creating the necessary database tables. These will be published when you run the vendor publish command for migrations.
Usage
Models
Permission Model
The Permission model represents individual permissions in your application.
Key features:
- Automatic slug generation
- Wildcard permissions support
- Scope support
Usage example:
Role Model
The Role model represents roles that can be assigned to users and associated with permissions.
Key features:
- Automatic slug generation
- Role hierarchy support
- Permission checking methods
Usage example:
Middleware
HandleInertiaRequests Middleware
The HandleInertiaRequests
middleware is designed to work with Inertia.js applications, sharing the authenticated
user's permissions with the frontend.
Key Features
-
Inertia Request Detection: Automatically detects if the current request is an Inertia request.
-
Permission Sharing: Shares the authenticated user's permissions with Inertia, making them available on the frontend.
- Caching: Uses Laravel's cache system to store user permissions, improving performance by reducing database queries.
How it Works
- The middleware checks if the request is an Inertia request.
- If it is, it retrieves the authenticated user's permissions.
- These permissions are then shared with Inertia, making them available in the frontend as
auth.permissions
.
Usage
To use this middleware, add it to your app/Http/Kernel.php
file in the web
middleware group:
Once added, the middleware will automatically share the authenticated user's permissions with your Inertia frontend.
Accessing Permissions in the Frontend
Example: In your Vue components, you can access the user's permissions like this:
This middleware enhances the integration between your Laravel backend and Inertia.js frontend, making it easier to implement permission-based UI logic.
PermissionMiddleware
The PermissionMiddleware
is designed to protect routes based on user permissions. It checks if the authenticated user
has the required permission(s) before allowing access to a route.
Key Features
- Route Protection: Allows you to specify required permissions for accessing specific routes.
- Multiple Permission Support: Can check for multiple permissions, granting access if the user has any of them.
- Authentication Check: Ensures the user is authenticated before checking permissions.
- JSON Response Support: Returns a JSON response for unauthorized actions if the request expects JSON.
Usage
To use this middleware, you can add it to your routes or controllers:
-
In your
app/Http/Kernel.php
, add an alias for the middleware: -
Use it in your routes:
- Or use it in your controllers:
Multiple Permissions
You can specify multiple permissions. The middleware will allow access if the user has any of the specified permissions:
Handling Unauthorized Access
When a user doesn't have the required permission:
- For regular requests, it will abort with a 403 status and "Unauthorized action." message.
- For JSON requests, it will return a JSON response with a 403 status and an "Unauthorized action." message. This middleware provides a robust way to implement permission-based access control in your Laravel application, integrating seamlessly with the Laravel Role Permission Manager package.
RoleMiddleware
The RoleMiddleware
is designed to protect routes based on user roles. It checks if the authenticated user has the
required role(s) before allowing access to a route.
Key Features
- Route Protection: Allows you to specify required roles for accessing specific routes.
- Multiple Role Support: Can check for multiple roles, granting access if the user has any of them.
- Authentication Check: Ensures the user is authenticated before checking roles.
- JSON Response Support: Returns a JSON response for unauthorized actions if the request expects JSON.
Usage
To use this middleware, you can add it to your routes or controllers:
-
In your
app/Http/Kernel.php
, add an alias for the middleware: -
Use it in your routes:
- Or use it in your controllers:
Multiple Roles
You can specify multiple roles. The middleware will allow access if the user has any of the specified roles:
Handling Unauthorized Access
When a user doesn't have the required role:
- For regular requests, it will abort with a 403 status and "Unauthorized action." message.
- For JSON requests, it will return a JSON response with a 403 status and an "Unauthorized action." message. This middleware provides a straightforward way to implement role-based access control in your Laravel application, complementing the permission-based middleware and integrating seamlessly with the Laravel Role Permission Manager package.
Facade
The package provides a facade for easy access to role and permission management functions.
Key methods:
createRole(string $name, string $slug, ?string $description = null, ?Role $parent = null): Role
createPermission(string $name, string $slug, ?string $description = null): Permission
givePermissionToRole(Role $role, Permission|string $permission, ?string $scope = null): void
revokePermissionFromRole(Role $role, Permission|string $permission, ?string $scope = null): void
syncPermissions(Role $role, array $permissions): void
hasPermissionTo(mixed $user, string $permission, ?string $scope = null): bool
getSubRoles(Role $role): Collection
grantPermissionToRoleAndSubRoles(Role $role, Permission|string $permission): void
revokePermissionFromRoleAndSubRoles(Role $role, Permission|string $permission): void
Usage example:
These new methods allow for more granular control over role hierarchies and permissions. The getSubRoles method retrieves all sub-roles of a given role, while grantPermissionToRoleAndSubRoles and revokePermissionFromRoleAndSubRoles apply permission changes to both the specified role and all its sub-roles.
Artisan Commands
The package provides several Artisan commands to manage roles and permissions:
- create:role: Create a new role
- create:permission: Create a new permission
- assign:permission: Assign a permission to a role
- remove:permission: Remove a permission from a role
- list:roles-permissions: List all roles and permissions
- sync:permissions: Synchronize permissions for a role
Automatic Route Registration
By default, the package registers the following routes:
GET /roles
: List all rolesGET /permissions
: List all permissionsGET /user/{userId}/roles
: Get roles for a specific userGET /user/{userId}/permissions
: Get permissions for a specific userGET /user/{userId}/permissions/{scope}
: Get scoped permissions for a specific user
These routes are protected by middleware and can be accessed via the RolePermissionController
included with the
package.
Customizing Route Registration
You can customize the route registration by setting the use_package_routes
configuration option to false. it is set to
true by default.
Authorization Policies
The Laravel Role Permission Manager package comes with pre-defined authorization policies for the Role and Permission models. These policies are automatically registered when you use the package.
Policy Registration
The policies are registered in the AuthServiceProvider
that comes with the package:
Using the Policies
These policies allow you to control who can perform various actions on roles and permissions. You can use them in your controllers or other parts of your application like this:
Or in a Blade template:
Custom Policies
If you need to customize these policies, you can publish them to your application:
This will copy the policies to your app/Policies directory, where you can modify them as needed.
Available Policy Methods
Both the RolePolicy and PermissionPolicy typically include methods for standard CRUD operations:
- viewAny: Determine whether the user can view any roles/permissions.
- view: Determine whether the user can view the role/permission.
- create: Determine whether the user can create roles/permissions.
- update: Determine whether the user can update the role/permission.
- delete: Determine whether the user can delete the role/permission.
Remember to adjust your application's authorization logic in these policies according to your specific requirements.
Frontend Integration
Accessing Permissions in the Frontend
Permissions are shared with the Inertia.js frontend and can be accessed in Vue components.
Vue Permission Helper Functions
The package includes TypeScript-friendly utility functions for managing user permissions in Vue components.
Key Functions
-
can(permission: string, scope: string | null = null): boolean
- Checks if the user has a specific permission, optionally within a given scope.
-
getScopedPermissions(scope: string): Permission[]
- Retrieves all permissions for a specific scope.
-
hasAnyPermissionInScope(scope: string): boolean
- Checks if the user has any permission in a given scope.
-
hasAllPermissions(permissionSlugs: string[]): boolean
- Checks if the user has all specified permissions.
-
hasAnyPermission(permissionSlugs: string[]): boolean
- Checks if the user has any of the specified permissions.
getAllScopes(): string[]
- Retrieves all unique scopes from the user's permissions.
Usage in Vue Components
To use these helpers in your Vue components:
-
Import the helper functions:
- Use them in your component:
Note on Permissions Data
These helpers expect the permissions data to be available on window.Laravel.permissions. Ensure this data is properly populated on your frontend, typically by sharing it through your backend views or API responses.
This TypeScript module provides a robust and type-safe way to manage permissions in your Vue.js frontend, complementing the backend permission management provided by the Laravel Role Permission Manager package.
React Permission Hooks
For React applications, the package provides a custom hook usePermissions.
Key Features
- Inertia.js Integration: Works seamlessly with Inertia.js to access shared permissions data.
- Memoized Functions: All permission checks are memoized for improved performance.
- Scoped Permissions: Supports checking permissions within specific scopes.
Usage
To use the usePermissions
hook in your React components:
-
Import the hook:
- Use it in your component:
Available Functions
- can(permission: string, scope?: string): boolean
Checks if the user has a specific permission, optionally within a given scope.
- hasAnyPermission(permissions: string[]): boolean
Checks if the user has any of the specified permissions.
- hasAllPermissions(permissions: string[]): boolean
Checks if the user has all of the specified permissions.
- getScopedPermissions(scope: string): Permission[]
Retrieves all permissions for a specific scope.
- hasAnyPermissionInScope(scope: string): boolean
Checks if the user has any permission in a given scope.
Note on Permissions Data
This hook expects the permissions data to be available in the Inertia page props under auth.permissions. Ensure this data is properly shared from your Laravel backend when using Inertia.js.
This React hook provides a convenient and type-safe way to manage permissions in your React frontend when using Inertia.js, complementing the Laravel Role Permission Manager package's backend functionality.
Testing
To run the tests, use:
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
- [Godspower Oduose](https://github.com/rockblings)
- [All Contributors](../../contributors)
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-role-permission-manager with dependencies
spatie/laravel-package-tools Version ^1.16
illuminate/contracts Version ^10.0||^11.0