CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

24 April, 2021

Two Best Laravel Packages to Manage Roles Permissions

 Programing Coderfunda     April 24, 2021     Packages, php     No comments   

 

Two Best Laravel Packages to Manage Roles Permissions

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:

  • Laravel-permission by Spatie
  • Bouncer by Joseph Silber

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:

  • Zizaco / entrust
  • Romanbican / roles
  • Kodeine / Laravel-acl

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!

Database Structure

This is where the packages are quite different. Spatie’s package has these tables:

Two Best Laravel Packages to Manage Roles Permissions

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:

Two Best Laravel Packages to Manage Roles Permissions

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.

Available Methods

These packages do offer really similar functionality, so let’s compare in details.

Create Roles/Permissions/Abilities

Spatie

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']);

Bouncer

You can create role and ability, and assignment all in one sentence:

Bouncer::allow('admin')->to('ban-users');

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

Spatie

$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']);

Bouncer

$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

Spatie

$user->givePermissionTo('edit articles');
$user->givePermissionTo('edit articles', 'delete articles');

$user->revokePermissionTo('edit articles');

Bouncer

$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

Spatie

Check roles

$user->hasRole('writer');
$user->hasAnyRole(Role::all());
$user->hasAllRoles(Role::all());

Check permissions

$user->can('edit articles');
$role->hasPermissionTo('edit articles');

Bouncer

Check roles

$user->isAn('admin');
$user->isA('subscriber', 'editor');
$user->isAll('editor', 'moderator');
$user->isNot('subscriber', 'moderator');

Check permissions

Bouncer::allows('edit articles')

This section is pretty similar in both packages, with no clear winner.

Blade Commands

Spatie

@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

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.

Caching

Spatie

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

Bouncer

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:

Bouncer::refresh();

Alternatively, you can refresh the cache only for a specific user:

Bouncer::refreshFor($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.

Overall Conclusion

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.

Spatie’s Advantages:

  • 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

Bouncer’s Advantages:

  • 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:

  • Laravel 5.4 admin panel based on Spatie Laravel-permission
  • Laravel 5.4 admin panel based on Bouncer
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Laravel Lambo – A package to quickly scaffold out a new project Laravel Lambo is a new package by Tighten.co that allows you to quickly scaffold out a new Laravel application from your terminal.It works … Read More
  • Laravel Passport – Easily setup your own OAuth2 server Creating your own OAuth server can be difficult and Laravel 5.3 comes with a free optional package called Passport that is a full OAut… Read More
  • Laravel Scout is now open for developer testing     Laravel Scout is a driver based full-text search for Eloquent that is going to be available when Laravel 5.3 launches.The dri… Read More
  • Easily deleting old soft-deleted records with Quicksand When building applications, there are times when you would like to allow users to remove data from their view but keep the record in the databas… Read More
  • TNTSearch Driver is now available for Laravel Scout Laravel Scout was just opened for developer testing and TNTStudio has already launched a new package for implementing their TNTSearch … Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...
  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Enabling authentication in swagger
    I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. S...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Generate a Detailed Application Report with Laravel Decomposer - 5/23/2025
  • Streamline Conditional Logic with Laravel's Fluent Conditionable Trait - 5/18/2025
  • Sublime Text Releases Update With Support for Right Sidebar - 5/22/2025
  • Enhance Email Validation with Laravel's Fluent Email Rule Object - 5/18/2025
  • Locale-aware Number Parsing in Laravel 12.15 - 5/21/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda