Spatie Laravel Permission

Spatie Laravel Permission

A powerful and flexible package for managing roles and permissions in Laravel applications

INSTALLATION
$composer require spatie/laravel-permission

spatie/laravel-permission is one of the most popular Laravel packages for handling roles and permissions in a clean, flexible, and powerful way.

It allows you to easily assign roles and permissions to users, models, or guards, while keeping your authorization logic organized and scalable.

This package is widely used in production applications and integrates seamlessly with Laravel's authorization system.

Key Features

1

1️⃣ Role & Permission Management

Define roles and permissions dynamically and assign them to users or models with ease.

CODE
$user->assignRole('admin');
$user->givePermissionTo('edit articles');
2

2️⃣ Multiple Guards Support

Supports multiple authentication guards (web, api, admin, etc.) out of the box.

CODE
'guards' => ['web', 'api']
3

3️⃣ Blade Directives

Use expressive Blade directives to control UI access.

CODE
@role('admin')
    <p>Admin content</p>
@endrole
4

4️⃣ Middleware Integration

Protect routes easily using built-in middleware.

CODE
Route::middleware(['role:admin'])->group(function () {
    //
});

Installation

1

Step 1: Install the package

CODE
composer require spatie/laravel-permission
2

Step 2: Publish configuration & migrations

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

Step 3: Run migrations

CODE
php artisan migrate
4

Step 4: Add trait to User model

CODE
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
}

Usage

1

Check permissions

CODE
if ($user->can('edit articles')) {
    //
}
2

Assign role on registration

CODE
$user->assignRole('user');

Security Notes

Always validate user permissions on both frontend and backend.

Avoid assigning high-privilege roles dynamically without proper checks.

Cache permissions for better performance in production.

Changelog

Supports Laravel 10, 11, 12

Improved cache handling

Enhanced multi-guard compatibility

Alternatives

Laravel Gates & Policies (Native)

Silber Bouncer

Laratrust