Back to blog

Implementing a UI for Spatie Laravel Permissions

Feb 26, 2024
.
Samuel Trstenský

Are the users of your system all the same? Should each of your users be able to perform the same actions? I bet not. That's why you should consider implementing roles and permission management. But what is the correct approach for your Laravel project?

When considering the approach to implementing permissions in Laravel, most of us will probably turn to Spatie’s Laravel Permissions package. With just a hit of the enter key, you will have options like:

This is very cool, but soon you will realize that the only way to manage permissions is by using commands or directly through the database. Is that enough for you? If so, you can stop reading now :). However, it's more likely that you won't want to have permissions editable solely through the database. If you're working on a complex project, you'll need to consider creating a user-friendly UI for permission management.

You could start from scratch and create one on your own, but let's be honest, you probably don’t want to. You're looking to solve this task as quickly as possible. Don't worry, Craftable PRO has your back.

Craftable PRO’s Roles & Permissions Management

As someone once said, seeing is believing, so I want to show you how you can implement the Craftable PRO permissions UI in your existing project.

If you are starting your project from scratch with Craftable PRO, it comes directly with roles management— based on the Spatie Laravel permissions package — and a very nice UI.

However, there might be cases where we initially thought role management wouldn't be necessary, and manually creating roles would be enough. But then, the client realizes they want a nice UI and the ability to create custom roles with a custom set of permissions. In such cases, it's never too late for Craftable PRO! The roles and permissions will be automatically loaded, even if they are already defined.

Let's look at an example. Imagine you are developing a discussion forum. In this project, you will create a new custom role, which you will call 'Moderator'.

Role::create(['name' => 'Moderator']);

What is the role when it has no permissions? You will probably want the moderator to be able to show, edit, and delete comments. Let's define these permissions:

Permission::create(['name' => 'comment.show']); 
Permission::create(['name' => 'comment.edit']); 
Permission::create(['name' => 'comment.delete']);

Now, the dreadful news will arrive: the client wants a UI form permission management. But as you know, there's an easy solution ;).

Just add Craftable PRO into your project and call

php artisan craftable-pro:install

… and let the magic happen.

The magic

As you can see in the picture below, Craftable PRO automatically creates roles for Administrator and Guest and preserves previously created roles. You will also be able to create a new role directly from the Craftable PRO UI.