DEV Community

Tanzim Ibthesam
Tanzim Ibthesam

Posted on

Laravel Api create Users,Posts with Role Permissions using Gates no packages

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
Imagedescription
In User.php
Imagedescription
Note Carefully
In migrations folder keep the Role migrations above User migrations
Imagedescription

Role Migrations
This is how your Role migrations would look like
Imagedescription

User Migrations
This is how your User migrations would look like
Imagedescription
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.
Imagedescription
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
Imagedescription
You can also check your database it will appear like this
Imagedescription
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
Imagedescription
So create an AuthController aand also a RegisterRequest

php artisan make:request RegisterRequest
RegisterRequest
Imagedescription
Here return true inside authorize function in RegisterRequest

In AuthController
Imagedescription
Login method
LoginRequest
Imagedescription

Imagedescription
Logout Method
Imagedescription

4.Register a User
At first let us register an Admin **
Imagedescription
So here we already registered an admin.
**Now let us register a Author

Imagedescription
Now let us Register a Editor
Imagedescription
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');
In AuthServiceProvider.php
Imagedescription

Here only user with role_id of 1 can create a user
AuthController.php
Here we can write
Imagedescription

Sanctum middleware was not included cause we needed to create the first user.
Lets login with Super Admin credentials and generate a token
Imagedescription
In Register authorization part of postman we need to select Bearer Token and just copy and paste the token
Imagedescription
Body of postman
Imagedescription
In case of no token
Imagedescription
It shows unauthenticated
** Logging out with Token**
Imagedescription
Logging in as an author trying to create a user
Now lets login as a Author
Imagedescription
We see here a token is generated
With same token when we try to create a user
Body of request
Imagedescription
Showing token
Imagedescription
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
Imagedescription
in UserController.php
Imagedescription
We are using the same gate like we did with
When we try to delete with author
Imagedescription
It shows unauthorized
Login As admin and generate a new token
Imagedescription
Using the token to delete user
Imagedescription
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
Imagedescription
In Post.php
Imagedescription
Migrations
Imagedescription
PostRequest.php
Imagedescription

** 6.Permissions to create,edit and delete post**

i.Admin and author can create posts only
In AuthServiceProvider.php
Imagedescription

PostController.php
Imagedescription
Admin sending a create request
Imagedescription
Its created
Lets logout and create a new post with author
Imagedescription
Token generated with Author
Imagedescription
Posts created by author
Imagedescription
Post successfully created
Lets logout and try to create post with Editor
Token created by editor
Imagedescription
Create posts by Editor
Imagedescription
'Editor cant create a post its says unauthorized'
Imagedescription

ii. Editor and Admin can edit all posts,Author can only edit his own post
Imagedescription
Editor trying to edit his post and other post
Imagedescription
Imagedescription
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
Imagedescription

When he tries to edit someone elses post in this case Admins post
Imagedescription
It says its unauthorized
Imagedescription
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**
Imagedescription
Login and generate a token for admin
Imagedescription
Admin Deleting a post
Imagedescription
Logging out and logging in as an user
Imagedescription
We see here with same token when we try to delete a post it says unauthorized
Imagedescription
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)

Collapse
 
saanchitapaul profile image
Sanchita Paul

Why after registration it's returning a welcome page. Neither it's showing any error?

Collapse
 
lucianonascimento profile image
Luciano

try to set in your header a field "Accept" with this value "application/json"

Collapse
 
tanzimibthesam profile image
Tanzim Ibthesam

You must have made any error and are you using postman?

Collapse
 
groznia3 profile image
groznia

I have tried all of the step above. But why I always got "Invalid credentials" whenever I try to login in my postman?

Collapse
 
lucianonascimento profile image
Luciano • Edited

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 :

Hash::make('yourpassword')
Enter fullscreen mode Exit fullscreen mode