Laravel: Rate-Limit API Routes with Throttle
Protect your Laravel API from abuse with the built-in throttle middleware — limit requests per minute per user or IP.
Check a Sanctum token's abilities in middleware, so only tokens with the right permission can reach a route.
25 lines · Updated Nov 26, 2026
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckTokenAbility
{
public function handle(Request $request, Closure $next, string $ability)
{
$user = $request->user();
if (! $user || ! $user->currentAccessToken()
|| ! $user->tokenCan($ability)) {
abort(403, 'This token does not have the required ability.');
}
return $next($request);
}
}
// In routes/api.php — register the middleware as 'ability'
// Route::post('/posts', [PostController::class, 'store'])
// ->middleware(['auth:sanctum', 'ability:posts:create']);
Laravel Sanctum lets you give each API token a set of abilities (also called scopes) — for example orders:read or orders:write. That way a token you hand to a reporting tool can read data but never change it. This snippet checks those abilities in middleware, so every protected route rejects tokens that do not have the right permission before your controller even runs.
$user->createToken('reporting', ['orders:read']).Authorization: Bearer header is missing or the token was revoked.Sanctum or Passport? Sanctum is simpler and fits most first-party apps and mobile APIs. Passport is for full OAuth2 servers where third parties request access.
Related: Rate-limit API routes · OWASP Top 10 explained
Save as app/Http/Middleware/CheckTokenAbility.php and register it in bootstrap/app.php with an alias like ability. Then add it to routes with the ability name, for example ability:posts:create.
Share this snippet
Protect your Laravel API from abuse with the built-in throttle middleware — limit requests per minute per user or IP.
Generate a sitemap.xml from your database in Laravel — always up to date, no file to maintain by hand.
Send WhatsApp messages from Laravel through a provider API — order updates, OTPs and alerts in a few lines.