Complete Guide to Authentication, API, and Role/Permission Management in Laravel 12

This tutorial covers installing Laravel 12, configuring built-in and API authentication with Sanctum, setting up API routes manually, and implementing role-based access control (RBAC) using Spatie’s Laravel Permission packag.


Introduction

Laravel 12 introduces a new bootstrap approach where both routing and middleware are defined in bootstrap/app.php. In this guide, you’ll learn how to:

  • Install and configure Laravel 12
  • Scaffold web authentication via Laravel UI or Jetstream
  • Install and secure API routes manually with Sanctum
  • Implement RBAC with Spatie Laravel Permission

Step 1: Install and Set Up Laravel

Begin by creating a fresh Laravel 12 project:

composer create-project --prefer-dist laravel/laravel laravel-app

Then:

cd laravel-app

This sets up the directory structure, including bootstrap/ and routes/ folders.


Step 2: Set Up Web Authentication

Laravel 12 itself does not include an auth scaffold. Choose one of the following:

Option 1: Laravel UI


composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev
php artisan migrate
    

This installs Bootstrap-based login, registration, and password reset views.

Option 2: Jetstream


composer require laravel/jetstream
php artisan jetstream:install livewire
npm install && npm run dev
php artisan migrate
    

Jetstream adds advanced features like two-factor auth and session management.


Step 3: Install and Set Up API Routes in Laravel 12

In Laravel 12, API routes are not available by default. We need to manually set up the API scaffolding and configure the routes.

Install API Scaffolding:

To set up API routes manually, run the following command:

php artisan install:api

This command installs the necessary scaffolding to handle API routes in your Laravel app.

Define a Protected API Route


/* routes/api.php */
use Illuminate\Support\Facades\Route;

/* Protected by Sanctum */
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:sanctum');
    

The auth:sanctum middleware ensures only valid API tokens can access this endpoint.


Step 4: Configure Middleware in bootstrap/app.php

All route and middleware configuration occurs here in Laravel 12:


/* bootstrap/app.php */
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        using: function () {
            // Web routes
            Route::middleware('web')
                 ->group(base_path('routes/web.php'));
            // API routes
            Route::middleware('api')
                 ->prefix('api')
                 ->name('api.')
                 ->group(base_path('routes/api.php'));
        }
    )
    ->withMiddleware(function (Middleware $middleware) {
        // Sanctum stateful middleware
        $middleware->prepend('api', EnsureFrontendRequestsAreStateful::class);
        // Spatie permission middleware aliases
        $middleware->alias([
            'role' => RoleMiddleware::class,
            'permission' => PermissionMiddleware::class,
            'role_or_permission' => RoleOrPermissionMiddleware::class,
        ]);
    })
    ->create();
    

Step 5: Set Up API Authentication with Sanctum

Sanctum provides token-based authentication for SPA and mobile apps:

Install Sanctum

composer require laravel/sanctum

Publish Config & Migrate

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
    

Step 6: Implement Role & Permission Management

Use Spatie’s package to manage roles and permissions:

Install & Publish


composer require spatie/laravel-permission
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate
    

Spatie v6 uses the singular Middleware namespace.

Configure in bootstrap/app.php


// (Refer to the middleware alias section above)
    

Define Roles & Permissions Seeder


/* database/seeders/RolesAndPermissionsSeeder.php */
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        Permission::create(['name'=>'view users']);
        Permission::create(['name'=>'edit users']);

        $admin = Role::create(['name'=>'admin']);
        $user  = Role::create(['name'=>'user']);

        $admin->givePermissionTo(['view users','edit users']);
        $user->givePermissionTo('view users');
    }
}
    
php artisan db:seed --class=RolesAndPermissionsSeeder

Step 7: Protect Routes by Role/Permission

Use the aliases defined to guard routes:


// routes/web.php
Route::middleware(['role:admin'])->get('/admin', function(){
    return view('admin.dashboard');
});

Route::middleware(['permission:view users'])->get('/users', function(){
    return view('users.index');
});
    

Conclusion

In Laravel 12, all routing and middleware configuration is centralized in bootstrap/app.php—no Kernel.php edits are required. You’ve now learned to:

  • Install and set up **authentication** in Laravel 12
  • Set up **API routes** manually
  • Configure **Sanctum** for API authentication
  • Use **Spatie Laravel Permission** for role-based access control (RBAC)

This approach aligns with Laravel 12’s modern bootstrap structure and ensures a clean, maintainable project setup.

apione.in

Comments

Leave a Reply