So I was always in a confusion regarding roles and permissions in Laravel. But I have come across different issues but I thought why not write something since it would even help me also. So most popular way of implementing roles and permissions is using Laravel Permissions by Spatie. Its a great package and most are likely to use it. I wanted to understand things and tried with Gate and Policy which is one of my most favorite feature of Laravel Gate.We are using API here so if you dont know how to authenticate apis in Laravel using Sanctum please read my Making Api CRUD(Create,Read,Update,Delete) with Laravel 8 n API Authentication with sanctum learn things like generating tokens,authentication,authorization.
1.At first lets create a User Roles Model relationship
At first We will create a One to Many Relation with Roles and user.
At first create a Model,Factory,Controller for both Roles and Users
php artisan make:model Role -fms this creates factories,migration and seeder and seeders too
For Users lets just make a Controller which is a resource Controller.
php artisan make:controller UserController --resource
The user migrations and Models are given by default and now lets create a Role Controller
php artisan make:controller UserController --resource
One to Many Relations
Here Role has Many Users and User BelongToRole
In Role.php

In User.php

Note Carefully
In migrations folder keep the Role migrations above User migrations

Role Migrations
This is how your Role migrations would look like

User Migrations
This is how your User migrations would look like

Run php artisan:migrate
2.Now lets create some dunny data with RoleSeeder
Go to database/seeder/RoleSeeder.php if you dont find any dont worry run php artisan make:seeder RoleSeeder that is you have not created seeder.

Here we will have 3 roles
1.Super Admin
2.Author
3.Editor
Now only run the RoleSeeder
php artisan db:seed --class=RoleSeeder.This is the way if you only want to run a specific seeder.
If you have done everything correct you will see

You can also check your database it will appear like this

If you are using anything else there will be a different view.So now we have our roles.
3.Register Users with Roles
I am showing here the Controllers for both Login and Register

So create an AuthController aand also a RegisterRequest
php artisan make:request RegisterRequest
RegisterRequest

Here return true inside authorize function in RegisterRequest
In AuthController

Login method
LoginRequest

4.Register a User
At first let us register an Admin **

So here we already registered an admin.
**Now let us register a Author

Now let us Register a Editor

Here we see by assigning different role_id we have created 3 users with 3 roles
5.User Creation Permission with Gate
Here we will create some permissions with help of Gate. If you dont know about Gate please read a bit bout Gates in Laravel documentation.
i.Only Super Admin can create a user
Here at first in api.phpwe need to change register route a bit
Route::post('/register',[AuthController::class,'register'])->middleware('auth:sanctum');
InAuthServiceProvider.php
Here only user with role_id of 1 can create a user
AuthController.php
Here we can write

Sanctum middleware was not included cause we needed to create the first user.
Lets login with Super Admin credentials and generate a token

In Register authorization part of postman we need to select Bearer Token and just copy and paste the token

Body of postman

In case of no token

It shows unauthenticated
** Logging out with Token**

Logging in as an author trying to create a user
Now lets login as a Author

We see here a token is generated
With same token when we try to create a user
Body of request

Showing token

So here we can see anyone without Super Admin role_id no one cant create a user.While trying its shows unauthorized
ii.Only Admin can delete a user
In the same way an admin can delete a User.
We need to make a User Resource Controller
php artisan make:controller UserController --resource
In api.php

in UserController.php

We are using the same gate like we did with
When we try to delete with author

It shows unauthorized
Login As admin and generate a new token

Using the token to delete user

So we can see user can only be deleted by admin.
5.Create,edit,delete posts
So we will create Posts and provide permissions based on roles
Make Controller and Model **
**php artisan make:model Post -mc
php artisan make:request PostRequest
In PostRequest.php
Relation with User Posts OneToMany
In User.php

In Post.php

Migrations

PostRequest.php

** 6.Permissions to create,edit and delete post**
i.Admin and author can create posts only
In AuthServiceProvider.php

PostController.php

Admin sending a create request

Its created
Lets logout and create a new post with author

Token generated with Author

Posts created by author

Post successfully created
Lets logout and try to create post with Editor
Token created by editor

Create posts by Editor

'Editor cant create a post its says unauthorized'

ii. Editor and Admin can edit all posts,Author can only edit his own post

Editor trying to edit his post and other post


Though its a bit hard to see you can see Editor being able to edit any post as they have the same token
Lets logout and create a new token logging as a Author

When he tries to edit someone elses post in this case Admins post

It says its unauthorized

Now its edited that is he can create his own post
If you logout and login as admin you will see the same thing
**
iii. Admin can only delete all posts**

Login and generate a token for admin

Admin Deleting a post

Logging out and logging in as an user

We see here with same token when we try to delete a post it says unauthorized

So I guess this covers a lot on creating roles and permissions. Hopefully I will try to implement these with Policies and in future with Vue,Inertia.



Top comments (5)
Why after registration it's returning a welcome page. Neither it's showing any error?
You must have made any error and are you using postman?
try to set in your header a field "Accept" with this value "application/json"
I have tried all of the step above. But why I always got "Invalid credentials" whenever I try to login in my postman?
I had the same problem but not sure if the cause is the same, but anyway, in my case it's because password was not hashed, try save password using this :