Zeshan
Zeshan

Reputation: 2657

Laravel 5.2 Cache increment issue with expiration time

I am adding a key to Cache for x minutes on first http request and then keep incrementing on next requests.

Issue I face is while incrementing, cache expire time also gets reset, I need to retain the expiry time. I also show expiry time in terms of seconds.

Below is my code:

$key = $input['device_id'];
if(! $attempts = Cache::get($key))
{
   Cache::put($key, 1, Carbon::now()->addMinutes(5));
}
else
{
  Cache::increment($key);
}

Upvotes: 0

Views: 1048

Answers (1)

apokryfos
apokryfos

Reputation: 40653

You can extend the built-in middleware ThrottlesRequests and attach it to your login route :

 class MyThrottleRequests extends \Illuminate\Routing\Middleware\ThrottlesRequests {

      protected function resolveRequestSignature($input) {
              return $input->device_id; //I think this is what you mean to use right?
      }

 }

You can then specify it in your defined middleware in Kernel.php

  protected $routeMiddleware = [
       // Existing ones
       'throttleDeviceId' => MyThrottleRequests::class
  ]; 

You can then use it on your required routes as:

  \Route::any("/route/to/throttle",/* Route definition */)->middleware("throttle:<max requests>,<within time>");

Upvotes: 1

Related Questions