Laravel permissioning system(Role based access control)

Laravel permissioning system(Role based access control)

Mar 04, 2019 / Moody Developer

Using ACL is a much common requirement for almost every project ranging from few users to big CRM's.

Laravel has multiple options for using ACL for your project or website.

Spatie has a nice & simple package for role based ACL which works with your existing user model. This package allows you to manage user permissions and roles in a database.

Once installed you can do stuff like this:

// Adding permissions to a user
$user->givePermissionTo('edit articles');

// Adding permissions via a role
$user->assignRole('writer');

If you're using multiple guards, every guard will have its own set of permissions and roles that can be assigned to the guard's users. You can even this package with Laravel & Lumen.

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:

Here are some examples how we can use it :

// You may also pass an array
$user->givePermissionTo(['edit articles', 'delete articles']);

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

$user->syncPermissions(['edit articles', 'delete articles']);

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

$user->hasPermissionTo('1');
$user->hasPermissionTo(Permission::find(1)->id);
$user->hasPermissionTo($somePermission->id);

$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

There are so many things you can do with with package. Head over & add it to your project.


Similar Articles

Moving existing PHPUnit tests to PEST in Laravel application

Moving existing PHPUnit tests to PEST in Laravel application

How to move existing PHPUnit tests to PEST within your Laravel application.
Read more...
How to do multi tenant application with Laravel

How to do multi tenant application with Laravel

How to do multi tenant application with Laravel. Have single laravel setup for multiple applications
Read more...
What is new to Laravel 6?

What is new to Laravel 6?

Today Laravel 6 has finally officially released. Let's have a detailed look at what is changing in Laravel 6.
Read more...