Laravel 10: implementing Custom Middleware for Rate Limiting API Requests Based on User Type
I'm deploying to production and I'm upgrading from an older version and I'm trying to implement a custom middleware in Laravel 10 to rate limit API requests based on user types..... My goal is to allow 'premium' users 100 requests per hour while 'regular' users only get 60 requests. However, I encounter an scenario where the rate limiting seems to apply to all users equally, regardless of their type. Here's the middleware I created: ```php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Cache; use Illuminate\Http\Request; class RateLimitMiddleware { public function handle(Request $request, Closure $next) { $user = $request->user(); $rateLimit = $user && $user->isPremium() ? 100 : 60; $key = 'rate_limit:' . $user->id; $requests = Cache::get($key, 0); if ($requests >= $rateLimit) { return response()->json(['behavior' => 'Too Many Requests'], 429); } Cache::put($key, $requests + 1, now()->addHour()); return $next($request); } } ``` I've registered the middleware in the kernel as follows: ```php protected $routeMiddleware = [ 'rate.limit' => \App\Http\Middleware\RateLimitMiddleware::class, ]; ``` And I've applied it to my routes: ```php Route::middleware(['auth', 'rate.limit'])->group(function () { Route::get('/api/user/data', [UserController::class, 'getData']); }); ``` Despite this setup, I'm observing that both user types are being limited to 60 requests per hour when I log their usage. I've debugged the middleware and verified that the `isPremium` method correctly identifies the user type. Can anyone point out what I'm missing or if there's a better approach to achieve this feature? For context: I'm using Php on Ubuntu 22.04. What's the best practice here? I'm working with Php in a Docker container on Ubuntu 22.04. Any ideas how to fix this?