Loading image

Blogs / Programming

Complete Guide to Spatie Role and Permission in Laravel 11

Complete Guide to Spatie Role and Permission in Laravel 11

  • showkat ali
  • 0 Comments
  • 105 View

Implementing Roles and Permissions in Laravel 11 with Spatie: A Real-World Example

In this article, we will go through a practical example of how to manage users, roles, permissions, and items using the Spatie Role and Permission package in Laravel 11.

We’ll build a simple system where:

  • Users can have different roles like admin, editor, and customer.
  • Each role has certain permissions like creating, editing, and deleting items.
  • We will use Blade templates to display content based on user permissions.

1. Install and Set Up Spatie Role and Permission Package

To begin, let's first install the spatie/laravel-permission package.

composer require spatie/laravel-permission

Publish the configuration and migration files:

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

Run the migrations:

php artisan migrate

Now we have the necessary tables for roles, permissions, and the pivot tables to link them with users.


2. Define Roles and Permissions

We will define a few roles and permissions for our example. Consider the following roles and permissions:

  • Roles:

    • adminHas all permissions.
    • editorCan create and edit items.
    • customer: Can only view items.
  • Permissions:

    • create items: Allows creating items.
    • edit items: Allows editing items.
    • delete items: Allows deleting items.
    • view items: Allows viewing items.

Seeding Roles and Permissions

Let’s create a seeder to set up the roles and permissions.

// database/seeders/RoleAndPermissionSeeder.php

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RoleAndPermissionSeeder extends Seeder
{
    public function run()
    {
        // Create permissions
        Permission::create(['name' => 'create items']);
        Permission::create(['name' => 'edit items']);
        Permission::create(['name' => 'delete items']);
        Permission::create(['name' => 'view items']);

        // Create roles and assign permissions
        $admin = Role::create(['name' => 'admin']);
        $editor = Role::create(['name' => 'editor']);
        $customer = Role::create(['name' => 'customer']);

        $admin->givePermissionTo(Permission::all());

        $editor->givePermissionTo(['create items', 'edit items', 'view items']);
        
        $customer->givePermissionTo('view items');
    }
}

 

Run the seeder:

 
php artisan db:seed --class=RoleAndPermissionSeeder

 


3. Assign Roles and Permissions to Users

Now let’s assign these roles to users. For instance, we’ll assign the admin⁣role to the first user and the editor⁣role to the second user.

 

// Assigning roles to users

use App\Models\User;
use Spatie\Permission\Models\Role;

$user1 = User::find(1);  // Find the first user
$user1->assignRole('admin');  // Assign admin role

$user2 = User::find(2);  // Find the second user
$user2->assignRole('editor');  // Assign editor role

 You can also assign permissions directly to users if needed:

$user2->givePermissionTo('create items');  // Assign specific permission to user

 

4. Using Roles and Permissions in Controllers

In the controllers, we can check the user’s roles and permissions before performing actions. Let's implement CRUD functionality for items.

Create Item Controller

Only users with the create items permission can create new items.

// app/Http/Controllers/ItemController.php

namespace App\Http\Controllers;

use App\Models\Item;
use Illuminate\Http\Request;

class ItemController extends Controller
{
    public function create()
    {
        $this->authorize('create items');  // Check if user has permission

        return view('items.create');
    }

    public function store(Request $request)
    {
        $this->authorize('create items');  // Check if user has permission

        $item = new Item();
        $item->name = $request->name;
        $item->save();

        return redirect()->route('items.index');
    }
}

 

Edit Item Controller

Only users with the edit items permission can edit an existing item.

public function edit(Item $item)
{
    $this->authorize('edit items');  // Check if user has permission

    return view('items.edit', compact('item'));
}

public function update(Request $request, Item $item)
{
    $this->authorize('edit items');  // Check if user has permission

    $item->update($request->all());

    return redirect()->route('items.index');
}

 

Delete Item Controller

Only users with the delete items permission can delete items.

public function destroy(Item $item)
{
    $this->authorize('delete items');  // Check if user has permission

    $item->delete();

    return redirect()->route('items.index');
}

5. Using Roles and Permissions in Routes

You can protect routes based on roles or permissions. For example:

Route for Creating Items

use App\Http\Controllers\ItemController;

Route::get('/items/create', [ItemController::class, 'create'])
    ->middleware('permission:create items');  // Only users with this permission can access
Route::post('/items', [ItemController::class, 'store'])
    ->middleware('permission:create items');  // Only users with this permission can store

 

Route for Viewing Items:

Route::get('/items', [ItemController::class, 'index'])
    ->middleware('permission:view items');  // Only users with the permission can view items

 

6. Using Roles and Permissions in Blade Views

In Blade views, you can show or hide sections of content based on roles or permissions.

Show Create Item Button for Editors and Admins

@can('create items')  <!-- Check if the user has the 'create items' permission -->
    <a href="{{ route('items.create') }}">Create Item</a>
@endcan

Show Edit Item Button for Editors and Admins

@can('edit items')  <!-- Check if the user has the 'edit items' permission -->
    <a href="{{ route('items.edit', $item->id) }}">Edit</a>
@endcan

Show Delete Item Button for Admins

@can('delete items')  <!-- Check if the user has the 'delete items' permission -->
    <form action="{{ route('items.destroy', $item->id) }}" method="POST">
        @csrf
        @method('DELETE')
        <button type="submit">Delete</button>
    </form>
@endcan

7. Conclusion

In this example, we demonstrated how to implement roles and permissions in a Laravel 11 application using the Spatie Role and Permission package. Here’s a quick summary:

  • Roles like admin, editor, and customer are created and assigned to users.
  • Permissions like create items, edit items, and view items are created and associated with the roles.
  • The controller checks permissions before performing actions like creating, editing, or deleting items.
  • Blade views use @can to show or hide buttons based on the user’s permissions.

This gives you complete flexibility in building a system that controls who can do what in your application. You can easily extend this by adding more roles, permissions, and actions as needed for your app.

  • Programming
showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance.

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

A Step-by-Step Guide: How to Integrate CoinGate with Laravel 10

A Step-by-Step Guide: How to Integrate CoinGate with Laravel 10

showkat ali
/
Programming

Read More
Top 10+ Best Web Frameworks to Learn for a Successful Web Development Career

Top 10+ Best Web Frameworks to Learn for a Successful Web Development Career

showkat ali
/
Programming

Read More
How to Create a Custom Signup Form in Django 5.0

How to Create a Custom Signup Form in Django 5.0

Qadir Hassan
/
Programming

Read More
Polymorphic Relationships in Laravel: A Comprehensive Guide with Example

Polymorphic Relationships in Laravel: A Comprehensive Guide with Example

showkat ali
/
Programming

Read More
Laravel API Performance Boost: How to Use whenLoaded() for Efficient Relationship Loading

Laravel API Performance Boost: How to Use whenLoaded() for Efficient Relationship Loading

showkat ali
/
Programming

Read More
Simplify Image Uploads: Creating a Generic Image Function in Laravel 10

Simplify Image Uploads: Creating a Generic Image Function in Laravel 10

showkat ali
/

Read More