Cookie

This site uses tracking cookies used for marketing and statistics. Privacy Policy

Contact

Step by step guide for using Laravel-permissions package from spatie

Spatie's Laravel-Permission is the industry standard for managing user roles and capabilities in Laravel. The best practice is to assign permissions to roles, then assign those roles to users. You install it with Composer, add the HasRoles trait to your User model, seed your roles and permissions, assign roles to users, then enforce permissions in Blade, middleware, and controllers.

Mukesh Ram

Mukesh Ram

Publish Date: September 16, 2022 Last Updated: October 14, 2026

Summarize with AI:

  • ChatGPT
  • Google AI
  • Perplexity
  • Grok
  • Claude

Introduction

As the Founder and CEO at Acquaint Softtech, an Official Laravel Partner, I have built role-based access control into Laravel apps for clients across the USA, UK, Europe, Australia, and New Zealand. You need to define roles and permissions to control access to your database. Fortunately, Laravel has made it easy for you to do so. Here is how.

The go-to tool for this is the spatie/laravel-permission package. It is the most trusted way to manage who can see and do what inside your app, and this guide walks you through it step by step, with the exact commands and code.

This Article Is for You If...

  • You want a clear spatie/laravel-permission tutorial with code.-
  • You are a developer, CTO, or founder adding roles and permissions.
  • You want the official Spatie package setup done right.
  • You need a role: admin middleware and Blade @can examples.
  • You want best practices for a Super-Admin and permission checks.
  • You want a proven Laravel partner to build secure access control.


This tutorial follows the official Spatie package docs and current Laravel 11 and 12 practices. If you prefer, you can read the official spatie/laravel-permission docs alongside this guide. The package is also on GitHub, which is handy when you want to inspect the source or track issues.

If you would rather have this built and secured for you, our dedicated software development teams set up role-based access control the right way from day one.

What is Laravel-permission?

What is Laravel-permission?

Not every user needs to have access to all the data in the database. Let's take the example of a college website. The access to the data and permissions allowed to a teacher will be different from that of a student. Why? Because their roles and responsibilities are different.

Laravel-permission allows you to do the same with your database. It lets you manage users' roles and permissions in your database. Let's see how you can do the same step-by-step.

What is Spatie?

What is Spatie?

Spatie is a Belgian web-development company well known for its high-quality open-source Laravel packages. Its most popular package, spatie/laravel-permission, is the industry standard for roles and permissions. Spatie also maintains many other trusted packages (for media, backups, and more), which is why the name comes up so often in the Laravel world. So when people ask "what is spatie laravel data," they usually mean one of these first-party Spatie packages that make common tasks simple and reliable.

Why Use the Spatie Laravel-Permission Package?

Why Use the Spatie Laravel-Permission Package?

Spatie's laravel-permission is popular because it is battle-tested, well-documented, and saves you from writing fragile custom access code. Rolling your own roles and permissions may look simple at first, but it quickly turns messy as your app grows. Here is why teams pick Spatie instead.

  • Proven and trusted: used by hundreds of thousands of Laravel apps, so bugs are found and fixed fast.

  • Clean database structure: it ships ready-made roles, permissions, and pivot tables so you do not design them yourself.

  • Simple, readable API: methods like assignRole(), givePermissionTo(), and can() read like plain English.

  • Flexible checks: guard by permission, by role, in Blade, in middleware, or in controllers, whatever fits.

  • Built-in caching: permissions are cached automatically, so access checks stay fast at scale.

Setting this foundation up correctly the first time saves months of rework later, which is exactly what our discovery workshop services help teams get right before a single feature is built.

Step 1: Installation and Setup

Run the Composer command in your project terminal to install the package.

composer require spatie/laravel-permission

Publish the database migrations and configuration file:

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

Run your migrations to create the necessary tables (roles, permissions, and the pivot tables):

php artisan migrate

If you are upgrading an older Laravel app before adding this, our version upgrade services get you to a supported version safely first.

Step 2: Configure the User Model

Open your app/Models/User.php file and add the HasRoles trait. This provides access to all the package's relationship methods.

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Spatie\Permission\Traits\HasRoles; // 1. Import the trait

class User extends Authenticatable

{

    use Notifiable, HasRoles; // 2. Use the trait

    // ... rest of your model code

}

Step 3: Seed Roles and Permissions

The safest way to create your permission structure is through a database seeder so that every environment stays synced. Create a seeder:

php artisan make:seeder RolesAndPermissionsSeeder

Open database/seeders/RolesAndPermissionsSeeder.php and populate it using the Spatie models. Configure your seeder to clear cached permissions, create permissions (for example, editing and creating articles, or managing users), define roles like writer and admin, and assign permissions accordingly. Then execute the seeder:

php artisan db:seed --class=RolesAndPermissionsSeeder

Need an extra pair of expert hands for this? You can hire Laravel developers from Acquaint Softtech, onboarded within 48 hours.

Step 4: Assigning Roles to Users

You can assign, remove, or sync roles directly on your user instances within your application logic:

$user = User::find(1);

$user->assignRole('writer');

$user->removeRole('writer');

$user->syncRoles(['writer', 'moderator']);

Creating Roles and Permissions in Code

Inside your seeder or a controller, you create roles and permissions with the Spatie models, then attach permissions to roles. Here is a simple example:

use Spatie\Permission\Models\Role;

use Spatie\Permission\Models\Permission;

// create permissions

Permission::create(['name' => 'edit articles']);

Permission::create(['name' => 'publish articles']);

// create a role and give it permissions

$role = Role::create(['name' => 'writer']);

$role->givePermissionTo('edit articles');

// or give many at once

$role->syncPermissions(['edit articles', 'publish articles']);

You can also give a permission directly to a user without a role, though assigning through roles is the recommended best practice:

$user->givePermissionTo('edit articles');

$user->revokePermissionTo('edit articles');

Checking Roles and Permissions

Once roles and permissions are assigned, you check them with simple methods. Prefer checking permissions over roles so your logic stays flexible.

$user->hasRole('writer');            // true or false

$user->hasAnyRole(['writer','admin']);

$user->can('edit articles');         // permission check (preferred)

$user->hasPermissionTo('edit articles');

$user->getRoleNames();               // collection of role names

$user->getAllPermissions();          // all permissions the user has

For teams that want this wired into a larger product with clean architecture, our software development outsourcing gives you a full Laravel team without the hiring overhead.

Step 5: Enforcing Permissions in Your App

Prioritize checking for permissions over roles to keep your app flexible. There are three main places to enforce them.

  • Blade views: use @can directives to conditionally render UI elements.

  • Routes and middleware: register middleware aliases in bootstrap/app.php for Laravel 11+ and apply them to secure route groups (for example, role:admin).

  • Controllers: perform inline authorization checks using $user->can() and abort if unauthorized.

Getting these checks right is a security matter, and our support and maintenance services keep access control tested and patched over time.

Blade view example

Show or hide parts of your UI based on what the user can do:

@can('edit articles')

    <a href="/articles/edit">Edit</a>

@endcan

@role('admin')

    <a href="/admin">Admin Panel</a>

@endrole

Route middleware example (Laravel 11 and 12)

First, register the middleware aliases in bootstrap/app.php, then protect your routes:

// bootstrap/app.php

->withMiddleware(function (Middleware $middleware) {

    $middleware->alias([

        'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,

        'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,

    ]);

})

// routes/web.php

Route::middleware(['role:admin'])->group(function () {

    // admin-only routes here

});

Controller example

Check inline and stop the request if the user is not allowed:

public function update(Request $request, Article $article)
{
    abort_unless($request->user()->can('edit articles'), 403);
    // ... update the article
}

A Note on Permission Caching

Spatie caches your permissions automatically to keep checks fast, so you must clear that cache whenever roles or permissions change in code. If you add a permission and it does not seem to work, a stale cache is usually the reason. Clear it with:

php artisan permission:cache-reset

Good seeders also clear the cache at the start, which is why the recommended seeder begins by resetting cached roles and permissions. This keeps every environment, from local to production, perfectly in sync.

Bonus: Defining a Super-Admin

To allow a Super-Admin role to bypass all permission checks automatically, configure a global Gate::before rule inside your app/Providers/AppServiceProvider.php boot method:

use Illuminate\Support\Facades\Gate;
 
public function boot(): void
{
    Gate::before(function ($user, $ability) {
        return $user->hasRole('Super-Admin') ? true: null;
    });
}

Common Spatie Methods Cheat Sheet

Here are the methods you will use most often, grouped by what they do.

Task

Method

What It Does

Assign role

$user->assignRole('admin')

Give a user a role

Remove role

$user->removeRole('admin')

Take a role away

Sync roles

$user->syncRoles([...])

Replace all roles at once

Give permission

$role->givePermissionTo('x')

Attach a permission to a role

Check permission

$user->can('x')

Preferred access check

Check role

$user->hasRole('admin')

Role-based check

Reset cache

permission:cache-reset

Clear cached permissions

A Real-World Example: The College Website

Remember the college website from earlier, where a teacher and a student need different access? Here is how that maps to Spatie in practice.

  1. Create permissions: view grades, edit grades, submit assignment, view courses.

  2. Create roles: a teacher role and a student role.

  3. Assign permissions to roles: the teacher gets edit grades and view grades; the student gets submit assignment and view courses.

  4. Assign roles to users: give each teacher the teacher role and each student the student role.

  5. Enforce it: wrap the grade-editing screen in @can('edit grades') so only teachers ever see it.

That is the whole model: permissions describe abilities, roles bundle them, and users receive roles. For a full student or campus portal built this way, you can hire Python developers or Laravel specialists from Acquaint Softtech to deliver it end to end.

Roles vs Permissions at a Glance

The core idea: permissions are specific abilities, roles are named bundles of permissions, and users get roles.

Concept

What It Is

Example

Permission

A single ability

edit articles

Role

A bundle of permissions

writer, admin

User

A person with roles

assignRole('writer')

Super-Admin

Bypasses all checks

Gate::before rule

For larger apps that need audit trails and complex hierarchies, our software product development services design access control that scales with your business.

Want secure roles and permissions done right?

Tell Acquaint Softtech about your app, and we will design and build clean, tested role-based access control on Laravel within a clear timeline and budget.

Case Study: A Verified Laravel Build

Case Study

Secure access control is only as good as the team behind it. As an Official Laravel Partner, Acquaint Softtech built a secure, role-based Laravel platform with clean permissions and reliable performance. Here is a simple snapshot, drawn from our verified reputation on Clutch.

Client

A business needing secure, role-based access control.

What we built

A Laravel app with Spatie roles and permissions, tested and hardened.

Why it matters

Right people, right access, with a clean Super-Admin and audit-friendly structure.

How we worked

A dedicated team, transparent process, and ongoing support.

Result

A secure, scalable platform delivered on time and built to grow.

Company-wide proof: Acquaint Softtech has delivered 1,300+ projects over 13+ years with 70+ in-house engineers and a 5-star rating across 60+ reviews on Clutch, as an Official Laravel and Laravel News Partner.

Why Choose Acquaint Softtech for Laravel Development

Choose a partner that is an Official Laravel Partner with public proof and an in-house team, and Acquaint Softtech is all three. Most clients save 60 to 75% versus hiring equivalent talent in the US, UK, or Australia, without cutting quality.

  • Official Laravel Partner: recognized expertise, plus Laravel News and Statamic Partner status.

  • Verified trust: 5-star Clutch rating across 60+ reviews and 1,300+ delivered projects.

  • In-house talent: 70+ full-time engineers, deployable within 48 hours.

  • Global reach: serving founders across the USA, UK, Europe, Australia, and New Zealand.

If you only need extra Laravel specialists on your own team, our IT staff augmentation services place vetted engineers within 48 hours.

Bottom Line

Managing roles and permissions does not have to be hard. With the spatie/laravel-permission package, you install it, add the HasRoles trait, seed your roles and permissions, assign roles to users, and enforce checks in Blade, middleware, and controllers. Add a Super-Admin bypass, and you have clean, scalable access control.

If you want this built and secured by experts, that is exactly the kind of work the team at Acquaint Softtech enjoys, so contact us to get started.

Ready to build secure Laravel access control?

Talk directly with Acquaint Softtech's founder in a free 30-minute session. You will leave with a clear plan for roles, permissions, and security on your Laravel app.

Frequently Asked Questions

  • How to use spatie permission in Laravel?

    Install it with composer require spatie/laravel-permission, publish and run the migrations, add the HasRoles trait to your User model, seed roles and permissions, assign roles with assignRole(), and enforce access with @can in Blade, role or permission middleware on routes, and $user->can() in controllers.

  • What is Spatie?

    Spatie is a Belgian web-development company famous for high-quality open-source Laravel packages. Its laravel-permission package is the industry standard for managing roles and permissions.

  • What is Spatie Laravel data?

    It refers to Spatie's first-party Laravel packages. Spatie maintains many trusted packages, and laravel-permission (for roles and permissions) is the best-known. People often use "spatie laravel" as shorthand for these packages.

  • What is the difference between roles and permissions?

    A permission is a single ability (like edit articles). A role is a named bundle of permissions (like writer or admin). You assign permissions to roles, then assign roles to users, and check permissions rather than roles for flexibility.

  • How do I create a Super-Admin that can do everything?

    Add a Gate::before rule in AppServiceProvider that returns true when the user has the Super-Admin role. This lets that role bypass all permission checks automatically.

  • Does spatie/laravel-permission work with Laravel 11 and 12?

    Yes. The package supports current Laravel versions. For Laravel 11+, you register middleware aliases in bootstrap/app.php and apply role or permission middleware to your route groups.

Mukesh Ram

I love to make a difference. Thus, I started Acquaint Softtech with the vision of making developers easily accessible and affordable to all. Me and my beloved team have been fulfilling this vision for over 15 years now and will continue to get even bigger and better.

Get Started with Acquaint Softtech

  • 13+ Years Delivering Software Excellence
  • 1300+ Projects Delivered With Precision
  • Official Laravel & Laravel News Partner
  • Official Statamic Partner

Related Blog

Secure Your Laravel Website: Here Are 5 Best Ways (2026 Update)

Laravel is highly secure by default, providing robust out-of-the-box protection against the web's most common vulnerabilities: SQL injection (via Eloquent and PDO binding), XSS (via Blade escaping), and CSRF (via tokens). But framework defaults are only half the battle. A secure production ecosystem also depends on proper configuration and secure coding: disable debug mode, protect your .env file, add rate limiting, enforce HTTPS, lock down mass assignment, and monitor your dependencies.

Mukesh Ram

Mukesh Ram

March 25, 2022

All You Need To Know About Laravel 9 (2026 Update)

Laravel 9 is a major PHP framework release that requires PHP 8.0 or higher and is built on Symfony 6. Released in February 2022, it introduced modern features like Symfony Mailer, anonymous stub migrations, enum route binding, and an improved routes: list console output. It is a long-term support (LTS) release, and while newer versions now lead, Laravel 9 remains a solid, well-understood base and a common starting point for a Laravel 9 to 10 upgrade.

Mukesh Ram

Mukesh Ram

February 23, 2022

Why Should You Pick Laravel For Web Development? (2026 Update)

Laravel is widely chosen for web development because it drastically accelerates production timelines while providing robust, enterprise-grade security out of the box. It removes repetitive boilerplate so developers can focus on unique business logic. The primary reasons to build with Laravel are accelerated time-to-market, ironclad security and reliability, a maintainable and scalable MVC architecture, and a rich ecosystem that supports business growth.

Mukesh Ram

Mukesh Ram

March 23, 2022

India (Head Office)

203/204, Shapath-II, Near Silver Leaf Hotel, Opp. Rajpath Club, SG Highway, Ahmedabad-380054, Gujarat

USA

7838 Camino Cielo St, Highland, CA 92346

UK

The Powerhouse, 21 Woodthorpe Road, Ashford, England, TW15 2RP

New Zealand

42 Exler Place, Avondale, Auckland 0600, New Zealand

Canada

141 Skyview Bay NE , Calgary, Alberta, T3N 2K6

Subscribe to new posts