Laravel 12 Roles and Permissions Setup: Complete Guide

Author

Kritim Yantra

Feb 28, 2025

Laravel 12 Roles and Permissions Setup: Complete Guide

In many web applications, controlling user access based on roles and permissions is crucial. For example, an admin might need full access to all features, while a regular user might only have limited permissions. Laravel, a powerful PHP framework, provides an excellent foundation for implementing such access control mechanisms.

In this blog post, we’ll explore how to add roles and permissions to a Laravel 12 application using the popular Spatie Laravel Permission package. This package simplifies the management of roles and permissions, making it easy to integrate into your Laravel projects.

By the end of this guide, you’ll know how to:

  • Install and configure the Spatie Laravel Permission package.
  • Create roles and permissions.
  • Assign roles and permissions to users.
  • Check for roles and permissions in your application.
  • Protect routes using middleware based on roles and permissions.

Prerequisites

  • A Laravel 12 project set up.
  • Composer installed.
  • Basic knowledge of Laravel concepts like models, migrations, and middleware.

Step 1: Install the Spatie Laravel Permission Package

The first step is to install the Spatie Laravel Permission package via Composer. Run the following command in your terminal:

composer require spatie/laravel-permission    

This will download the package and its dependencies into your project.

Step 2: Configure the Package

After installation, you need to publish the package's migration files. These migrations will create the necessary tables for roles, permissions, and their relationships. Run the following command:

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

This will copy the migration files to your database/migrations directory. Next, run the migrations to create the tables:

php artisan migrate    

Additionally, add the HasRoles trait to your User model. Open app/Models/User.php and include the trait as shown below:

use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    // ...
}    

Step 3: Create Roles and Permissions

Now that the package is set up, you can create roles and permissions. You can do this in various ways, such as through seeders, in your controllers, or via the console. For this example, we’ll use a seeder to create some roles and permissions.

First, create a new seeder:

php artisan make:seeder RolesAndPermissionsSeeder    

Open the newly created seeder file in database/seeders/RolesAndPermissionsSeeder.php and add the following code:

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

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Create roles
        $adminRole = Role::create(['name' => 'admin']);
        $editorRole = Role::create(['name' => 'editor']);
        $userRole = Role::create(['name' => 'user']);

        // Create permissions
        $createPostPermission = Permission::create(['name' => 'create post']);
        $editPostPermission = Permission::create(['name' => 'edit post']);
        $deletePostPermission = Permission::create(['name' => 'delete post']);

        // Assign permissions to roles
        $adminRole->givePermissionTo($createPostPermission);
        $adminRole->givePermissionTo($editPostPermission);
        $adminRole->givePermissionTo($deletePostPermission);

        $editorRole->givePermissionTo($createPostPermission);
        $editorRole->givePermissionTo($editPostPermission);

        $userRole->givePermissionTo($createPostPermission);
    }
}    

This seeder creates three roles (admin, editor, user) and three permissions (create post, edit post, delete post). It then assigns specific permissions to each role.

To run the seeder, use the following command:

php artisan db:seed --class=RolesAndPermissionsSeeder    

Step 4: Assign Roles to Users

Once roles are created, you can assign them to users. For example, in your controller or during user registration, you can assign a role like this:

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

$user = User::find(1);
$role = Role::findByName('admin');
$user->assignRole($role);    

Alternatively, you can assign roles directly when creating a user:

$user = User::create([
    'name' => 'Admin User',
    'email' => 'admin@example.com',
    'password' => bcrypt('password'),
]);

$user->assignRole('admin');    

Step 5: Check for Roles and Permissions

In your application, you can check if a user has a specific role or permission. For example, in a controller:

if ($user->hasRole('admin')) {
    // User is an admin
}

if ($user->hasPermissionTo('create post')) {
    // User can create posts
}    

You can also use Blade directives in your views for conditional rendering:

@role('admin')
    <p>You are an admin.</p>
@endrole

@permission('create post')
    <button>Create Post</button>
@endpermission    

Step 6: Use Middleware to Protect Routes

Update bootstrap/app.php:

->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,
        ]);
    })

Then, apply the middleware to your routes:

Route::group(['middleware' => ['role:admin']], function () {
    Route::get('/admin', [AdminController::class, 'index']);
});

Route::group(['middleware' => ['permission:create post']], function () {
    Route::get('/posts/create', [PostController::class, 'create']);
});    

Conclusion

Adding roles and permissions to your Laravel 12 application is straightforward with the Spatie Laravel Permission package. By following these steps, you can manage access control efficiently, ensuring that users can only perform actions they are authorized to do.

Remember to test your roles and permissions thoroughly to ensure they work as expected. For more advanced features, such as assigning permissions directly to users or using gates and policies, refer to the official documentation.

With this setup, your Laravel 12 application will be well-equipped to handle user authorization securely and effectively!

Tags

Laravel Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Continue with Google

Related Posts

Understanding SOLID Design Principles in Laravel (For Beginners)
Kritim Yantra Kritim Yantra
Feb 24, 2025
Laravel 12 Multi-Auth System: Implementing Separate Admin and User Tables
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel 12 & AdminLTE Integration: Setup Your Stunning Admin Dashboard
Kritim Yantra Kritim Yantra
Feb 28, 2025