Laratrust is a Laravel package designed to facilitate the implementation of roles and permissions within a Laravel application. It provides an easy and flexible way to manage user roles, permissions, and teams with a simple API and configuration process. Laratrust integrates seamlessly with Laravel's native authorization system, including policies and gates, allowing developers to leverage Laravel's built-in mechanisms alongside Laratrust's enhanced role and permission management capabilities.
Laratrust and Laravel Authorization Basics
Laravel's authorization system centers around two core concepts: policies and gates. Policies are classes that encapsulate authorization logic specifically for a given model or resource. Gates, on the other hand, are simple closure-based callbacks used for more general or application-wide authorization checks not necessarily tied to a model. Laratrust builds on this foundation by adding a comprehensive roles and permissions model that integrates with these native features.
Using Laratrust, roles and permissions can be assigned to users, and permissions can also be assigned to roles. This allows for flexible access control:
- Assign users multiple roles.
- Assign roles multiple permissions.
- Assign permissions directly to users.
- Support for teams and multiple user models.
This flexibility allows Laratrust to cover a wide range of access control scenarios while still working within Laravel's policies and gates system.
Integration with Laravel Policies
Policies in Laravel are designed to authorize actions on a particular model. When using Laratrust, you can leverage policies by checking if the authenticated user has certain roles or permissions tied to the action being authorized.
For example, consider a policy method controlling the update action on a Post model:
php
public function update(User $user, Post $post)
{
return $user->hasRole('admin') || $user->hasPermission('edit-post');
}
Here, Laratrust provides methods such as `hasRole` and `hasPermission` which integrate with Laravel's native policy methods. This means that the authorization logic inside policies can straightforwardly call Laratrust's role and permission checks, enabling granular control inside policy methods.
Since Laratrust supports Laravel's native `Gate` facade and policies out-of-the-box (starting from Laratrust version 6.x), you can confidently use Laratrust methods inside your policy classes without conflicts or the need for additional adapters.
Integration with Laravel Gates
Gates in Laravel provide a simpler, closure-based approach to authorization that can be used for actions not tied to a specific model. Laratrust fits within this system by allowing gate definitions that check roles and permissions managed by Laratrust.
Example of defining a gate using Laratrust's role/permission checks:
php
Gate::define('manage-users', function ($user) {
return $user->hasRole('admin');
});
Gate::define('edit-settings', function ($user) {
return $user->hasPermission('edit-settings');
});
This example shows how Laratrust's `hasRole` and `hasPermission` methods can be used directly inside gate callbacks to authorize actions. Since Laratrust dropped its own `can` method to align better with Laravel's native gates and policies, authorization calls like `$user->can('manage-users')` will also work seamlessly with Laratrust roles and permissions.
Authorization Checks in Controllers and Views
In Laravel, when using Laratrust, the typical authorization checks in controllers and views can directly utilize Laratrust's methods or Laravel's native authorization methods, due to the integration:
- In controllers, you can use:
php
$this->authorize('update', $post);
This triggers the relevant policy method that internally uses Laratrust's checks.
- You can also check roles or permissions directly on the user model:
php
if (Auth::user()->hasRole('admin')) {
// Execute admin-specific action
}
- Blade directives are also available and compatible:
blade
@role('admin')
// Admin content
@endrole
@permission('edit-post')
// Editable content
@endpermission
Because Laratrust integrates with Laravel's authorization system, it extends Laravel's native syntax and provides additional convenience methods for role-based access control.
How Laratrust Enhances Laravel's Policies and Gates
Laratrust enhances Laravel's policies and gates by adding:
1. Role-Based Permissions: Laravel policies and gates typically focus on permissions/actions, but Laratrust adds a full role system that can be used alongside permissions for grouping and managing user capabilities more effectively.
2. Multiple Role Assignments and Teams: Laratrust supports assigning multiple roles to a single user and organizing users into teams, which is not handled natively by Laravel's authorization system.
3. Caching and Event Support: Laratrust provides caching for roles and permissions checks, improving performance, and fires events when roles or permissions are added, removed, or synchronized on users or roles.
4. Admin Panel: Laratrust offers a simple admin panel for managing roles and permissions, allowing an easier user interface for authorization management that meshes with Laravel's policies and gates system.
5. Multiple Guards: Laratrust supports authorization across multiple authentication guards, allowing different user models to have roles and permissions handled appropriately within Laravel's policies and gates.
Practical Workflow Example
1. Define Roles and Permissions:**
Using Laratrust's API to create roles and permissions:
php
$adminRole = Role::create(['name' => 'admin']);
$editUserPermission = Permission::create(['name' => 'edit-user']);
2. Assign Roles and Permissions to Users:**
php
$user = User::find(1);
$user->attachRole($adminRole);
$user->attachPermission($editUserPermission);
3. Define Policies Using Laratrust Checks:**
Policy method example:
php
public function delete(User $user, Post $post) {
return $user->hasRole('admin') || $user->hasPermission('delete-post');
}
4. Define Gates Using Laratrust:**
php
Gate::define('access-admin-panel', function ($user) {
return $user->hasRole('admin');
});
5. Authorize in Controllers and Views:**
php
$this->authorize('delete', $post);
Or in blade templates:
blade
@role('admin')
@endrole
This workflow illustrates how Laratrust's API complements and integrates with Laravel's native gate and policy system, providing a robust, layered authorization mechanism.
Summary of Key Methods in Laratrust for Integration
- `hasRole($roleName)` â Checks if the user has a specified role.
- `hasPermission($permissionName)` â Checks if the user has a specified permission, either directly or via roles.
- `isAbleTo($permissionName)` â Alias for permission checks.
- `can($ability)` â Laratrust dropped this in favor of Laravel's native gate methods to avoid conflicts.
- `attachRole($role)` and `attachPermission($permission)` â To assign roles and permissions.
- `removeRole($role)` and `detachPermission($permission)` â To remove roles and permissions.
These methods are used within policies, gates, controllers, and views for authorization checks.
Considerations
Laratrust's compatibility with Laravel's policies and gates means that developers can start with Laravel's built-in authorization features and then layer on Laratrust for a more comprehensive role and permission system. Because the package utilizes Laravel's native authorization practices, it retains the clean, maintainable code structure and leverages Laravel's authorization middleware with minimal adjustments needed to existing policies or gates.
Laratrust's documentation and community support also emphasize that Laratrust works seamlessly with Laravel's native features and should be considered an enhancement rather than a replacement of Laravel's authorization system.
***
In conclusion, Laratrust integrates with Laravel's policies and gates system by providing powerful role and permission management functionality that can be called within Laravel's native authorization callbacks, policies, and gate definitions. It supports comprehensive features like multiple roles per user, teams, caching, events, and an admin panel, while fully embracing Laravel's authorization mechanisms for seamless use in complex applications.