To manage roles & permission, we going to add the Spatie Laravel-permission package to our Laravel Admin API.
The following steps are involved to install the Laravel permission package for our Laravel Admin API.
- Install Spatie Laravel-permission package
- Publish the configuration and migration file
- Running Migration
Install Spatie Laravel-permission package
Install the package using the composer command
./vendor/bin/sail composer require spatie/laravel-permission
Publish the configuration and migration file
The vendor:publish artisan command is used to publish the package configuration to the config folder. Also, copy the migration files to the migration folder.
./vendor/bin/sail artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
Running Migration
Run the migrations using artisan migrate
./vendor/bin/sail artisan migrate
Now we need to add some roles & permission. Then need to assign the role to users. So we need to create seeders.
I created an Admin core package with seeders and common functionality when I was working on Basic Laravel Admin Panel & Laravel Vue admin panel
Add the admin core package to our Admin API
./vendor/bin/sail composer require balajidharma/laravel-admin-core
This admin core package will install the Laravel Menu package. So run the below publish commands
./vendor/bin/sail artisan vendor:publish --provider="BalajiDharma\LaravelAdminCore\AdminCoreServiceProvider" ./vendor/bin/sail artisan vendor:publish --provider="BalajiDharma\LaravelMenu\MenuServiceProvider"
Now run the migration with the seeder
./vendor/bin/sail artisan migrate --seed --seeder=AdminCoreSeeder
The seeder throws the error
![](https://bandel.kendil.com/wp-content/uploads/2023/02/LARAVEL-3_1.webp)
We need to add HasRoles Traits in the user model. Open the app/Models/User.php
<?php . . . . . use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable, HasRoles; /** * The attributes that are mass assignable. *
Try again to run the seeder with migrate:fresh. So it will drop all tables and re-run all of our migrations.
./vendor/bin/sail artisan migrate:fresh --seed --seeder=AdminCoreSeeder
![](https://bandel.kendil.com/wp-content/uploads/2023/02/laravel-3_2.webp)
Open the Postman application and test the new user login. In the login, change the form data to the below email and password
Email — superadmin@example.com
Password — password
![](https://bandel.kendil.com/wp-content/uploads/2023/02/laravel-3_3.webp)
After login, runs the get user request. You will get the super admin details on the response.
![](https://bandel.kendil.com/wp-content/uploads/2023/02/laravel-3_4.webp)
We will create an API for Permission CRUD operations in the next blog.