Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

armingdev's avatar

Sanctum Roles & Permissions

Hi,

I have integrated Sanctum API Authorization for my app (Laravel API + React - as two separated projects) and I have made basic authentication. Now I need to work with roles and permissions. I saw Sanctum have abilities that I can attach to tokens. What is the best way to check abilities before it hit some action? Is there a better way then how its explained in documentation to check in contollers:


if ($user->tokenCan('server:update')) {
    //
}

I was looking for solution that Passport has, check on routes:


Route::get('/orders', function () {
    // Access token has both "check-status" and "place-orders" scopes...
})->middleware(['auth:api', 'scopes:check-status,place-orders']);

1 like
4 replies
TobiasS's avatar

Hi!

I have the same question. Did you find any solution/ best practice?

1 like
mkshingrakhiya's avatar

Yeah. You could use authorization gates or model policies to better manage authorization logic. Visit the official documents for it. Then see this amazing episode to dig deeper into it and to know how efficiently you can integrate authorization into your app.

fredrik@aringinnovation.se's avatar

I wrote a middleware to handle this exact problem, don't know if it's the best way but it was the fastest.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SanctumAbilitiesCheck
{
    public function handle($request, Closure $next, ...$abilities)
    {
        foreach ($abilities as $ability) {
            if (!$request->user()->tokenCan($ability)) {
                abort(400, 'Access denied');
            }
        }

        return $next($request);
    }
}

And is now usable in routes

Route::middleware('sanctum.abilities:can-read,can-write')->get('/', function () {
                dd("yay!");
});
5 likes

Please or to participate in this conversation.