How to install and setup spatie roles and permission in Laravel 11

By Ved Prakash N | Jun 07, 2024 | Laravel
Share :

https://www.fundaofwebit.com/post/how-to-install-and-setup-spatie-roles-and-permission-in-laravel-11

Install and Setup Laravel 11 Spatie roles and permissions tutorial step by step

In this post, you will be learning how to install and setup the Spatie Permission Package in Laravel 11.x version. Follow the below steps to get started:


Step 1: Install the Laravel Application

Install Laravel with the following command:

composer create-project laravel/laravel example-app

Setup the Database in .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel11
DB_USERNAME=root
DB_PASSWORD=


Install the Authentication package as per your requirement. So I will use Laravel Breeze

composer require laravel/breeze --dev

After successfully installing the Laravel Breeze package, run the below artisan command to install in the application.

php artisan breeze:install blade

once breeze:install is completed, run the below command to migrate the:

php artisan migrate


Step 2: Install the Spatie Package with the following command

2.1: install the package via composer

composer require spatie/laravel-permission

After installing the spatie larvel permission package.

2.2: Lets App the Service Providers as follows:

Go to the folder 'bootstrap/providers.php' file and paste the below code:

<?php

return [
    //...
    Spatie\Permission\PermissionServiceProvider::class,
];

2.3: Let's publish the migration and the config/permission.php config file with

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

2.4: Run the migration command:

php artisan migrate


Step 3: Setup the Middleware

This package comes with RoleMiddleware, PermissionMiddleware and RoleOrPermissionMiddleware middleware. You can add them inside your bootstrap/app.php file to be able to use them through aliases.

Go to the folder 'bootstrap/app.php' file and paste the below code:

->withMiddleware(function (Middleware $middleware) {

    $middleware->alias([
        'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
        'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
        'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
    ]);

})


Step 4: Add the necessary trait to your User model ( app/Models/User.php ) :
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
...


That's all dev.  We have seen how to install and Setup the Spatie Roles & Permission package in Laravel 11 

I hope this helped you.

https://www.fundaofwebit.com/post/how-to-install-and-setup-spatie-roles-and-permission-in-laravel-11

Share this blog on social platforms