Laravel Api create Users,Posts with Role Permissions using Gates no packages
Tags: laravel, php, role, permissions
Published: 2022-02-11 20:45:52

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](https://spatie.be/docs/laravel-permission/v5/introduction) 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](https://dev.to/tanzimibthesam/making-api-crud-create-read-update-delete-with-laravel-8-n-api-authentication-with-sanctum-19oh) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/stasf2d62d6j14leuslh.png)
In **User.php**
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t7oxp1jqdtghs2j793jd.png)
**Note Carefully**
In migrations folder keep the `Role migrations` above `User migrations`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k8akyduum5r8g3t2yhv6.png)
 
 **Role Migrations**
 This is how your Role migrations would look like 
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d3kd1xsz7geajizbroro.png)
 
 **User Migrations**
 This is how your User migrations would look like 
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ncf0dbezsq3cnhj1lp71.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hfpyx5t2nf7n1bw0sn8g.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/io7vv3yjz5stbt7wzy3g.png)
You can also check your database it will appear like this
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0c09noey3ec5483gt6ap.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xlbpuktn88e8h9kwple6.png)
`So create an AuthController aand also a RegisterRequest`

`php artisan make:request RegisterRequest`
`RegisterRequest`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j7byvc0bwp8ouujueiol.png)
Here return true inside authorize function in `RegisterRequest`
 
`In AuthController`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xsj6wh6tggcnaetfy7rk.png)
`Login method`
`LoginRequest`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j41fr51me3a5ispghqvj.png)
 
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7hoo6gji9ia4kb40jxt.png) 
**Logout Method**
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/08b3qvdly2r0hz21pxgp.png)

**4.Register a User**
**At first let us register an Admin **
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0yowg33h4c9a5w78mvc.png)
So here we already registered an admin. 
**Now let us register a Author**
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4idsjh6zucrzgytblbhs.png)
**Now let us Register a Editor**
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ciajjoumq19h6n9nmdt1.png)
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.php`we need to change register route a bit 
 

> Route::post('/register',[AuthController::class,'register'])->middleware('auth:sanctum');
In `AuthServiceProvider.php`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ozhy2rv80e2w3e7cpqj.png)

  
 Here only user with role_id of 1 can create a user
`AuthController.php`
Here we can write 
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rp50ord0asyyv0zsbskx.png)
 
 Sanctum middleware was not included cause we needed to create the first user.
`Lets login with Super Admin credentials and generate a token`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9kuiue8t0lxhz99ik5t.png)
In Register authorization part of postman we need to select `Bearer Token` and just copy and paste the token 
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b686dl25b9l5n287ycrh.png)
`Body of postman`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/93mqzrvr6vhlhaclkozb.png)
`In case of no token`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfltmrmhogqkayqxj7ss.png)
It shows unauthenticated
** Logging out with Token**
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1cnwy7y1x3bppc5gb0lu.png)
**Logging in as an author trying to create a user**
Now lets login as a Author
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/coo6hpw7x235ii0cenyr.png)
We see here a token is generated
With same token when we try to create a user 
`Body of request`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cu3996ztnduzz2iqbse2.png)
 `Showing token`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/30e1bwk8kpdvx1zwah5t.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sbnu6rpbem13598ce4jg.png)
`in UserController.php`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cmh167xuw8ll2n9x2n3m.png)
 We are using the same gate like we did with 
When we try to delete with author 
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogoqd2wo8u4d3k6s65ft.png)
 It shows `unauthorized`
`Login As admin and generate a new token`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/po1twr9wkcns026bc8ns.png)
 `Using the token to delete user`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikgn00g22ajr4fxqy51x.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/85yl6e9bogeju6x0c2d5.png)
`In Post.php`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5nesxxhhsnaszf0gkzd1.png)
`Migrations`
 ![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d77gnjns7rujhiwo64rs.png)
 `PostRequest.php`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5a3k6rcslqgtc3pf3id.png)
 
** 6.Permissions to create,edit and delete post**

 
i.Admin and author can create posts only
`In AuthServiceProvider.php`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ie29rcxak1w6va3sx9jp.png)

 `PostController.php`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehkmm6ryk23v7fswctj3.png)
`Admin sending a create request`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wf2mc21ubududgxutx9m.png)
 Its created
`Lets logout and create a new post with author`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eorw6alw21y6zhxo80vk.png)
 Token generated with Author
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cx1b420rin3r334un35c.png)
 `Posts created by author`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tm4e9qcc1ytb77evyi92.png)
 Post successfully created
`Lets logout and try to create post with Editor`
`Token created by editor`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bknhf5hqg1jq0it25n3.png)
 `Create posts by Editor`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mti2tndg29t3pzyxamh3.png)
'Editor cant create a post its says unauthorized'
 ![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aurs11mtfqzi5l9gpqzj.png)
 
 
ii. Editor and Admin can edit all posts,Author can only edit his own post
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yxe36ja1zrular8474dq.png)
 `Editor trying to edit his post and other post`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6d19rdk6mg1xrfapny79.png)
 ![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/obtcdat8x539gojxjnpw.png)
 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1o5c9vi13xl12vencgs.png)
 
 `When he tries to edit someone elses post in this case Admins post`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wsrwlmse6ztx2dom5hzx.png)
`It says its unauthorized`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xawb0up0ckv3ws1mzx77.png)
 `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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pdazck79igdg19p93tm.png)
`Login and generate a token for admin`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o305mqg1avvq0jgcpntx.png)
`Admin Deleting a post`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/grlaym4d5a9lvkoir4hq.png)
`Logging out and logging in as an user`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgyyzispsctehrpbdyua.png)
`We see here with same token when we try to delete a post it says unauthorized`
![Imagedescription](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ixrv8t0ap5evyumcwv66.png)
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.