Roles and permissions are an important part of many web applications. Laravel historically had a lot of packages for them, and improved the core code as well. So what is the situation on this market today? What packages are the best to use? I’ve picked two.
Why Do You Need Packages?
Let’s start from the beginning—Laravel has its own core logic for managing permissions. It was introduced in version 5.1.11 and has remained almost unchanged since. There we have things like:
- Gates and Policies
- $this->authorize() method
- @can and @cannot Blade commands
One might say it’s enough to have Laravel core and there’s no need for packages. This is part of the reason older packages are abandoned; core functions replaced them.
But there’s still an area where packages can help—to manage the permissions and roles, which is not easy in the core. And there are two packages which do that really well and are actively maintained:
Special mention: santigarcor/laratrust, which is a fork of unmaintained Entrust, and could be a strong third contestant. The problem with Laratrust is it replaces default Laravel commands with its own, so you wouldn’t be able to use Gates or @can syntax. Instead, you would need to use $user->can(‘edit-user’) or @permission Blade command. But if you don’t care about those extra syntax pieces, Laratrust is a great package. It also has Teams functionality, which is not present in Spatie’s or Bouncer packages.
There are a few more options, but they seem outdated and not that active. Still, you may want to watch them for a potential comeback:
Now, let’s get deeper into a “battle review” between two main contestants.
What Do These Packages Actually Do?
They give you an API to deal with roles and permissions more easily. Also, the final code is more reader-friendly and easier to understand.
Instead of creating all rules in Policies and Gates, which would be fragmented in a few different places, you would have code like this:
$user->givePermissionTo('edit articles'); // Spatie package $user->allow('ban-users'); // Bouncer package
Essentially, those two packages offer really similar functionality, with slightly different syntax and database structure. Let’s dig deeper and compare.
Installation and Usage
Both packages are installed similarly:
- Add to composer and install.
- Add a provider and facade (Bouncer) to config/app.php.
- Publish and run migrations.
- Add a special trait into User model (both packages use Traits).
- That’s it; use package’s methods (optionally including its classes where needed).
Packages assume you already have a default Laravel users DB table, but don’t have any structure for roles/permissions. They will add their own tables and fields.
Both packages have clear documentation, and there were no issues whatsoever. Great job done on README files!
This is where the packages are quite different. Spatie’s package has these tables:
Some explanations here:
- Field guard_name has default value web—package allows to use multiple guards.
- As you can see, there are two pivot tables for permissions—one with roles, and one with users.
- Field model_type has default value App\User so there’s no direct foreign key to users table, no other table has user_id field.
Now let’s look at Bouncer’s database:
Quite different, isn’t it? And even fewer relationships. Now, let me explain:
- What Spatie calls “permissions,” Bouncer calls “abilities.” And then the “permissions” table is a set of abilities attached to an “entity.”
- “Entity” (in all tables) is an object to assign abilities to. It may be a role or a user. Therefore, there is no direct relationship to user_id or users table; the same as with Spatie’s package.
- There are a few more fields different from the previous package: abilities.title, abilities.only_owned, and roles.level. They add some additional functionality, but it is not well explained in the README file.
- Spatie has guard fields which are not present in Bouncer.
All in all, Bouncer’s database structure seems a little more complicated and more difficult to understand at first, but with that comes a little more flexibility.
These packages do offer really similar functionality, so let’s compare in details.
You can use facades of the package as normal facades of Laravel:
use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; Role::create(['name' => 'writer']); Permission::create(['name' => 'edit articles']);
You can create role and ability, and assignment all in one sentence:
That’s it. Behind the scenes, Bouncer will create a Role model and an Ability model for you.
But you can also work with facades, too:
use Silber\Bouncer\Database\Ability; Ability::create(['name' => 'edit articles']);
As you can see, Bouncer has a little more functionality here with automatic “behind the scenes” model creation.
Assigning Roles to a User
$user->assignRole('writer'); $user->assignRole(['writer', 'admin']); $user->removeRole('writer');
Roles can also be synced:
// All current roles will be removed from the user and replace by the array given $user->syncRoles(['writer', 'admin']);
$user->assign('admin'); $user->assign(['writer', 'admin']); $user->retract('admin');
It’s great that both packages accept either individual roles or arrays.
But Spatie’s package wins here because of syncRoles functionality. It’s really useful; with Bouncer you need to perform it manually with a few operations.
Assigning Permissions/Abilities to a User
$user->givePermissionTo('edit articles'); $user->givePermissionTo('edit articles', 'delete articles'); $user->revokePermissionTo('edit articles');
$user->allow('ban-users'); $user->allow(['ban-users', 'edit-articles']);
You can pass the model name as a second argument.
Bouncer::allow($user)->to('edit', Post::class); Bouncer::allow($user)->to('edit', $post); $user->disallow('ban-users'); Bouncer::disallow($user)->to('delete', Post::class);
Similar functionality, but Bouncer offers the ability to pass the model class or its instance.
Checking Permissions/Roles for a User
$user->hasRole('writer'); $user->hasAnyRole(Role::all()); $user->hasAllRoles(Role::all());
$user->can('edit articles'); $role->hasPermissionTo('edit articles');
$user->isAn('admin'); $user->isA('subscriber', 'editor'); $user->isAll('editor', 'moderator'); $user->isNot('subscriber', 'moderator');
This section is pretty similar in both packages, with no clear winner.
@role('writer') I'm a writer! @else I'm not a writer... @endrole
@hasanyrole('writer|admin') I have one or more of these roles! @else I have none of these roles... @endhasanyrole
Bouncer does not add its own Blade directives.
More functionality by Spatie’s package. Of course, with both packages you can use default Laravel commands like @can and @endcan.
Role and permission data is automatically cached to speed up performance.
To manually reset the cache for this package, run:
php artisan cache:forget spatie.permission.cache
All queries executed by the bouncer are cached for the current request. If you enable cross-request caching, the cache will persist across different requests.
Whenever you need, you can fully refresh the bouncer’s cache:
Alternatively, you can refresh the cache only for a specific user:
Caching is a little more robust in Bouncer. Enabling/disabling cache is a good thing, and refreshing the cache for a particular user might come handy.
If you still expect a clear winner here, it’s not going to happen. Both packages are really good, and it’s a matter of preference.
Both of them have advantages in some functionality, but it’s more about the details.
- A little better documentation (some Bouncer’s methods aren’t mentioned in README)
- A little more understandable DB structure
- syncRoles() method instead of delete-insert way
- A few blade commands – @role and @hasanyrole
- Ability to use multiple guards
- Create role/ability and assign it—all in one sentence
- Allow or disallow permission based on model or its instance
- A little better caching mechanism
- A little more robust DB structure with a few more useful fields
If any of these details are really important to you, that could be the reason for your choice. Otherwise, pick Spatie or Bouncer, and you shouldn’t be disappointed.
P.S. Bonus Gift
Finally, both packages offer a set of functions to manage roles and permissions but don’t have any UI or admin panel to manage it. I’ve prepared a UI starter kit, based on both packages. You can use it as a boilerplate to manage roles and permissions.
Here are links to the GitHub repositories:Filed in: Laravel Packages / Authorization
Join 31,000+ others and never miss out on new tips, tutorials, and more.
PHP Released v7.2.0 Beta 1
Yesterday, the PHP team released the first beta of the 7.2.0 release. From the announcement this version builds on pr…
Laravel v5.4.29 is Released with Two New Blade Directives
Laravel V5.4.29 is now released and available. This is a maintenance release but it includes two new Blade Directives…