Laravel User Roles and Permissions Tutorial

by Saloni 4 minute read 13 views

Laravel assists in developing secure applications. Nearly half of the developers utilise permissions. Many companies trust Laravel to manage user roles and safeguard their applications effectively.

Key Points

  • More than 70% of companies depend on Laravel to develop secure and adaptable web frameworks.
  • Around 45% of developers assign role permissions to enhance user access and security.
  • Almost 80% of teams choose Laravel for projects requiring robust user role management features.

Modern businesses increasingly depend on custom web app development to build secure, scalable and adaptable applications. A key feature in any professional website project is robust user access control. Managing user roles and permissions guarantees that only authorised individuals can reach sensitive parts of your system.

In this article, we’ll walk through a step-by-step guide on how to implement user roles and permissions in Laravel, a popular PHP framework widely used by leading web development companies. We’ll use the powerful Spatie Laravel-Permission package to make the process smooth and secure. Whether you’re planning to hire a Laravel developer or working on your own, this guide is for you!

Step 1: Install Spatie Laravel-Permission Package

First, install the package via Composer. Run this command in your terminal:

                                        composer require spatie/laravel-permission
                                    

This package simplifies handling roles and permissions, an essential part of any custom web app development project.

Step 2: Publish Config and Migration Files

Next, publish the package’s configuration and migration files:

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

This will create:

  • Database migration files for the required tables
  • A configuration file at:

                                        config/permission.php
                                    

Publishing configuration files is a crucial step in any website development services workflow, allowing you to customize packages to match your app’s requirements.

Step 3: Run Migrations

Run the migrations to create the required tables:

                                        php artisan migrate
                                    

This generates several tables:

  • roles
  • permissions
  • model_has_roles
  • model_has_permissions
  • role_has_permissions

These tables store role and permission data crucial for implementing secure access control.

Step 4: Add HasRoles Trait to User Model

Next, add the HasRoles trait to your User model. Open:

app/Models/User.php

…and modify the code like this:

                                        use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
   use HasRoles;
}
                                    

This trait provides methods like assignRole(), hasRole(), and givePermissionTo(), making it easy to manage access control in your application. It’s one reason many businesses choose to hire Laravel developers for their complex apps.

Step 5: Create RolePermission Seeder

Let’s create a seeder to insert default roles and permissions.

Run:

                                        php artisan make:seeder RolePermissionSeeder
                                    

Then open:

database/seeders/RolePermissionSeeder.php

…and replace its contents with the following:

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


class RolePermissionSeeder extends Seeder
{
   public function run()
   {
       // Reset cached roles and permissions
       app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();


       // Create permissions
       $permissions = [
           'view users',
           'edit users',
           'delete users',
           'create users',
       ];


       foreach ($permissions as $permission) {
           Permission::firstOrCreate(['name' => $permission]);
       }


       // Create roles and assign permissions
       $admin = Role::firstOrCreate(['name' => 'admin']);
       $admin->givePermissionTo(Permission::all());


       $editor = Role::firstOrCreate(['name' => 'editor']);
       $editor->givePermissionTo(['view users', 'edit users']);
   }
}
                                    

Now, run the seeder:

                                        php artisan db:seed --class=RolePermissionSeeder
                                    

Using seeders makes development efficient—a key consideration for any web development company delivering a reliable custom development solution.

Step 6: Create UserRole Controller

Let’s create a controller to manage assigning roles and permissions.

Run:

                                        php artisan make:controller UserRoleController
                                    

Open the newly created controller file:

app/Http/Controllers/UserRoleController.php

…and update it as follows:

                                        use App\Models\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;


class UserRoleController extends Controller
{
   public function index()
   {
       return User::with('roles', 'permissions')->get();
   }


   public function assignRole(Request $request, $userId)
   {
       $user = User::findOrFail($userId);
       $role = $request->input('role'); // e.g., 'admin'
       $user->assignRole($role);


       return response()->json(['message' => "Role '{$role}' assigned to user."]);
   }


   public function givePermission(Request $request, $userId)
   {
       $user = User::findOrFail($userId);
       $permission = $request->input('permission'); // e.g., 'edit users'
       $user->givePermissionTo($permission);


       return response()->json(['message' => "Permission '{$permission}' granted to user."]);
   }
}
                                    

This controller makes it easy to:

  • List users and their roles
  • Assign roles
  • Grant specific permissions

These tasks are critical in any custom web app development workflow.

Step 7: Define Routes

Open your routes file, either:

  • routes/web.php (for web)
  • or routes/api.php (for API)

…and add the following:

                                        use App\Http\Controllers\UserRoleController;


Route::get('/users', [UserRoleController::class, 'index']);
Route::post('/users/{id}/assign-role', [UserRoleController::class, 'assignRole']);
Route::post('/users/{id}/give-permission', [UserRoleController::class, 'givePermission']);
                                    

This makes your role and permission functionality accessible via HTTP endpoints—a crucial feature for modern web apps developed by a professional web development company.

Step 8: Protect Routes with Middleware

To restrict routes to specific roles, you can use middleware.

Example:

                                        Route::middleware(['role:admin'])->group(function () {
   Route::get('/admin', function () {
       return 'Admin Dashboard';
   });
});
                                    

You can also use:

  • permission:edit users
  • role_or_permission:admin|edit users

These powerful middleware capabilities make Laravel ideal for enterprise-grade website development services.

Step 9: Use in Blade Views

Spatie’s package includes helpful Blade directives.

Example:

                                        @role('admin')
   <p>Welcome, Admin!</p>
@endrole


@can('edit users')
   <button>Edit User</button>
@endcan
                                    

This ensures that only users with the right permissions see certain buttons, links, or entire sections—a key security feature in custom web app development.

Step 10: Test Your Application

Finally, test your setup.

Run the Laravel server:

                                        php artisan serve
                                    

Then try these endpoints:

GET /users → Lists users with their roles and permissions
POST /users/{id}/assign-role → Assign a role to a user
POST /users/{id}/give-permission → Grant a specific permission to a user

Testing is a critical step before deploying any application, especially when you hire Laravel developers to build complex, permission-based systems.

Final Words

Managing user roles and permissions is essential for building secure web applications. Thanks to Spatie’s Laravel-Permission package, implementing this feature in Laravel is fast and efficient. Whether you’re working solo or collaborating with a web development company, these steps will help you keep your app secure and organized.

If you’re planning your next digital project, investing in expert website development services and choosing to hire Laravel developers can help you build a solid, secure, and scalable solution.

Tech Stack & Version

Frontend

  • HTML5
  • CSS3
  • JavaScript
  • Vue.js

Backend

  • Laravel
  • PHP
  • Node.js
  • MySQL

Deployment

  • DigitalOcean
  • AWS EC2
  • Linode
img

©2025Digittrix Infotech Private Limited , All rights reserved.