Download the PHP package geeky/laravel-permission without Composer
On this page you can find all versions of the php package geeky/laravel-permission. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download geeky/laravel-permission
More information about geeky/laravel-permission
Files in geeky/laravel-permission
Package laravel-permission
Short Description This is a fork of Spatia permission handling for Laravel 5.4 and up
License MIT
Homepage https://github.com/TheGeekyM/laravel-permission
Informations about the package laravel-permission
Associate users with permissions and roles
Sponsor
If you want to quickly add authentication and authorization to Laravel projects, feel free to check Auth0's Laravel SDK and free plan at https://auth0.com/overview. |
- Installation
- Usage
- Using "direct" permissions
- Using permissions via roles
- Using Blade directives
- Defining a Super-Admin
- Best Practices -- roles vs permissions
- Best Practices -- Using Policies
- Using multiple guards
- Using a middleware
- Using artisan commands
- Unit Testing
- Database Seeding
- Extending
- Cache
This package allows you to manage user permissions and roles in a database.
Once installed you can do stuff like this:
If you're using multiple guards we've got you covered as well. Every guard will have its own set of permissions and roles that can be assigned to the guard's users. Read about it in the using multiple guards section of the readme.
Because all permissions will be registered on Laravel's gate, you can check if a user has a permission with Laravel's default can
function:
Spatie is a web design agency in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
Installation
- Laravel
- Lumen
Laravel
This package can be used in Laravel 5.4 or higher. If you are using an older version of Laravel, take a look at the v1 branch of this package.
You can install the package via composer:
The service provider will automatically get registered. Or you may manually add the service provider in your config/app.php
file:
You can publish the migration with:
If you're using UUIDs or GUIDs for your User
models you can update the create_permission_tables.php
migration and replace $table->unsignedBigInteger($columnNames['model_morph_key'])
with $table->uuid($columnNames['model_morph_key'])
.
For consistency, you can also update the package configuration file to use the model_uuid
column name instead of the default model_id
column.
After the migration has been published you can create the role- and permission-tables by running the migrations:
You can publish the config file with:
When published, the config/permission.php
config file contains:
Lumen
You can install the package via Composer:
Copy the required files:
You will also need to create another configuration file at config/auth.php
. Get it on the Laravel repository or just run the following command:
Then, in bootstrap/app.php
, register the middlewares:
As well as the config file, service provider, and cache alias:
Now, run your migrations:
Usage
First, add the Spatie\Permission\Traits\HasRoles
trait to your User
model(s):
- note that if you need to use
HasRoles
trait with another model ex.Page
you will also need to addprotected $guard_name = 'web';
as well to that model or you would get an error
This package allows for users to be associated with permissions and roles. Every role is associated with multiple permissions.
A Role
and a Permission
are regular Eloquent models. They require a name
and can be created like this:
A permission can be assigned to a role using 1 of these methods:
Multiple permissions can be synced to a role using 1 of these methods:
A permission can be removed from a role using 1 of these methods:
If you're using multiple guards the guard_name
attribute needs to be set as well. Read about it in the using multiple guards section of the readme.
The HasRoles
trait adds Eloquent relationships to your models, which can be accessed directly or used as a base query:
The HasRoles
trait also adds a role
scope to your models to scope the query to certain roles or permissions:
The role
scope can accept a string, a \Spatie\Permission\Models\Role
object or an \Illuminate\Support\Collection
object.
The same trait also adds a scope to only get users that have a certain permission.
The scope can accept a string, a \Spatie\Permission\Models\Permission
object or an \Illuminate\Support\Collection
object.
Using "direct" permissions (see below to use both roles and permissions)
A permission can be given to any user:
A permission can be revoked from a user:
Or revoke & add new permissions in one go:
You can check if a user has a permission:
Or you may pass an integer representing the permission id
You can check if a user has Any of an array of permissions:
...or if a user has All of an array of permissions:
You may also pass integers to lookup by permission id
Saved permissions will be registered with the Illuminate\Auth\Access\Gate
class for the default guard. So you can
check if a user has a permission with Laravel's default can
function:
Using permissions via roles
A role can be assigned to any user:
A role can be removed from a user:
Roles can also be synced:
You can determine if a user has a certain role:
You can also determine if a user has any of a given list of roles:
You can also determine if a user has all of a given list of roles:
The assignRole
, hasRole
, hasAnyRole
, hasAllRoles
and removeRole
functions can accept a
string, a \Spatie\Permission\Models\Role
object or an \Illuminate\Support\Collection
object.
A permission can be given to a role:
You can determine if a role has a certain permission:
A permission can be revoked from a role:
The givePermissionTo
and revokePermissionTo
functions can accept a
string or a Spatie\Permission\Models\Permission
object.
Permissions are inherited from roles automatically. Additionally, individual permissions can be assigned to the user too. For instance:
In the above example, a role is given permission to edit articles and this role is assigned to a user.
Now the user can edit articles and additionally delete articles. The permission of 'delete articles' is the user's direct permission because it is assigned directly to them.
When we call $user->hasDirectPermission('delete articles')
it returns true
,
but false
for $user->hasDirectPermission('edit articles')
.
This method is useful if one builds a form for setting permissions for roles and users in an application and wants to restrict or change inherited permissions of roles of the user, i.e. allowing to change only direct permissions of the user.
You can list all of these permissions:
All these responses are collections of Spatie\Permission\Models\Permission
objects.
If we follow the previous example, the first response will be a collection with the delete article
permission and
the second will be a collection with the edit article
permission and the third will contain both.
Using Blade directives
This package also adds Blade directives to verify whether the currently logged in user has all or any of a given list of roles.
Optionally you can pass in the guard
that the check will be performed on as a second argument.
Blade and Roles
Check for a specific role:
is the same as
Check for any role in a list:
Check for all roles:
Alternatively, @unlessrole
gives the reverse for checking a singular role, like this:
Blade and Permissions
This package doesn't add any permission-specific Blade directives. Instead, use Laravel's native @can
directive to check if a user has a certain permission.
or
Defining a Super-Admin
We strongly recommend that a Super-Admin be handled by setting a global Gate::before
rule which checks for the desired role.
Then you can implement the best-practice of primarily using permission-based controls throughout your app, without always having to check for "is this a super-admin" everywhere.
See this wiki article on Defining a Super-Admin Gate rule in your app.
Best Practices -- roles vs permissions
It is generally best to code your app around permissions
only. That way you can always use the native Laravel @can
and can()
directives everywhere in your app.
Roles can still be used to group permissions for easy assignment, and you can still use the role-based helper methods if truly necessary. But most app-related logic can usually be best controlled using the can
methods, which allows Laravel's Gate layer to do all the heavy lifting.
Best Practices -- Using Policies
The best way to incorporate access control for access to app features is with Model Policies. This way your application logic can be combined with your permission rules, keeping your implementation simpler. You can find an example of implementing a model policy with this Laravel Permissions package in this demo app: https://github.com/drbyte/spatie-permissions-demo/blob/master/app/Policies/PostPolicy.php
Using multiple guards
When using the default Laravel auth configuration all of the above methods will work out of the box, no extra configuration required.
However, when using multiple guards they will act like namespaces for your permissions and roles. Meaning every guard has its own set of permissions and roles that can be assigned to their user model.
Using permissions and roles with multiple guards
When creating new permissions and roles, if no guard is specified, then the first defined guard in auth.guards
config array will be used. When creating permissions and roles for specific guards you'll have to specify their guard_name
on the model:
To check if a user has permission for a specific guard:
Note: When determining whether a role/permission is valid on a given model, it chooses the guard in this order: first the
$guard_name
property of the model; then the guard in the config (through a provider); then the first-defined guard in theauth.guards
config array; then theauth.defaults.guard
config.Note: When using other than the default
web
guard, you will need to declare whichguard_name
you wish each model to use by setting the$guard_name
property in your model. One per model is simplest.Note: If your app uses only a single guard, but is not
web
then change the order of your listed guards in yourconfig/auth.php
to list your primary guard as the default and as the first in the list of defined guards.
Assigning permissions and roles to guard users
You can use the same methods to assign permissions and roles to users as described above in using permissions via roles. Just make sure the guard_name
on the permission or role matches the guard of the user, otherwise a GuardDoesNotMatch
exception will be thrown.
Using blade directives with multiple guards
You can use all of the blade directives listed in using blade directives by passing in the guard you wish to use as the second argument to the directive:
Using a middleware
This package comes with RoleMiddleware
, PermissionMiddleware
and RoleOrPermissionMiddleware
middleware. You can add them inside your app/Http/Kernel.php
file.
Then you can protect your routes using middleware rules:
Alternatively, you can separate multiple roles or permission with a |
(pipe) character:
You can protect your controllers similarly, by setting desired middleware in the constructor:
Catching role and permission failures
If you want to override the default 403
response, you can catch the UnauthorizedException
using your app's exception handler:
Using artisan commands
You can create a role or permission from a console with artisan commands.
When creating permissions/roles for specific guards you can specify the guard names as a second argument:
When creating roles you can also create and link permissions at the same time:
Unit Testing
In your application's tests, if you are not seeding roles and permissions as part of your test setUp()
then you may run into a chicken/egg situation where roles and permissions aren't registered with the gate (because your tests create them after that gate registration is done). Working around this is simple: In your tests simply add a setUp()
instruction to re-register the permissions, like this:
Database Seeding
You may discover that it is best to flush this package's cache before seeding, to avoid cache conflict errors. This can be done directly in a seeder class. Here is a sample seeder, which first clears the cache, creates permissions and then assigns permissions to roles (the order of these steps is intentional):
Extending
If you need to EXTEND the existing Role
or Permission
models note that:
- Your
Role
model needs to extend theSpatie\Permission\Models\Role
model - Your
Permission
model needs to extend theSpatie\Permission\Models\Permission
model
If you need to REPLACE the existing Role
or Permission
models you need to keep the
following things in mind:
- Your
Role
model needs to implement theSpatie\Permission\Contracts\Role
contract - Your
Permission
model needs to implement theSpatie\Permission\Contracts\Permission
contract
In BOTH cases, whether extending or replacing, you will need to specify your new models in the configuration. To do this you must update the models.role
and models.permission
values in the configuration file after publishing the configuration with this command:
Cache
Role and Permission data are cached to speed up performance.
While we recommend not changing the cache "key" name, if you wish to alter the expiration time you may do so in the config/permission.php
file, in the cache
array. Note that as of v2.26.0 the cache
entry here is now an array, and expiration_time
is a sub-array entry.
When you use the built-in functions for manipulating roles and permissions, the cache is automatically reset for you, and relations are automatically reloaded for the current model record:
HOWEVER, if you manipulate permission/role data directly in the database instead of calling the supplied methods, then you will not see the changes reflected in the application unless you manually reset the cache.
Manual cache reset
To manually reset the cache for this package, you can run the following in your app code:
Or you can use an Artisan command:
Cache Identifier
TIP: If you are leveraging a caching service such as redis
or memcached
and there are other sites
running on your server, you could run into cache clashes between apps. It is prudent to set your own
cache prefix
in Laravel's /config/cache.php
to something unique for each application.
This will prevent other applications from accidentally using/changing your cached data.
Need a UI?
The package doesn't come with any screens out of the box, you should build that yourself. Here are some options to get you started:
-
Laravel Nova package by @vyuldashev for managing Roles and Permissions
-
Extensive tutorial for building permissions UI by Caleb Oki.
- How to create a UI for managing the permissions and roles
Testing
Upgrading
If you're upgrading from v1 to v2, @fabricecw prepared a gist which may make your data migration easier.
You will also need to remove your old laravel-permission.php
config file and publish the new one permission.php
, and edit accordingly.
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security-related issues, please email [email protected] instead of using the issue tracker.
Postcardware
You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.
We publish all received postcards on our company website.
Credits
- Freek Van der Herten
- All Contributors
This package is heavily based on Jeffrey Way's awesome Laracasts lessons on permissions and roles. His original code can be found in this repo on GitHub.
Special thanks to Alex Vanderbist who greatly helped with v2
, and to Chris Brown for his longtime support helping us maintain the package.
Alternatives
- Povilas Korop did an excellent job listing the alternatives in an article on Laravel News. In that same article, he compares laravel-permission to Joseph Silber's Bouncer, which in our book is also an excellent package.
- ultraware/roles takes a slightly different approach to its features.
Support us
Spatie is a web design agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
Does your business depend on our contributions? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-permission with dependencies
illuminate/auth Version ~5.3.0|~5.4.0|~5.5.0|~5.6.0|~5.7.0|~5.8.0
illuminate/container Version ~5.3.0|~5.4.0|~5.5.0|~5.6.0|~5.7.0|~5.8.0
illuminate/contracts Version ~5.3.0|~5.4.0|~5.5.0|~5.6.0|~5.7.0|~5.8.0
illuminate/database Version ~5.4.0|~5.5.0|~5.6.0|~5.7.0|~5.8.0