Search code examples
laravelthrottling

how can i throttle routes with parameter for diffrent ips


i created a page visit function that works with laravel throttle. each ip/user can increase visit counter every 60 minutes. i have a problem that can't apply throttle on different ids and throttle works on route only 1 time per 60 minutes and does'nt care about ids: (/home/visit/3 , /home/visit/4 ,.....): 1 time every 60 mins

route.php:

Route::post('/home/visit/{id}',[HomeController::class,'counter_visit'])->middleware('throttle:visit');

RouteServiceProvider.php

            RateLimiter::for('visit', function (Request $request) {
            return $request->user()
                ? Limit::perHour(1)->by($request->user()->id)
                : Limit::perHour(1)->by($request->ip());
                });

how can i apply throttle for each id like below?

/home/visit/3 : 1 time every 60 mins /home/visit/4 : 1 time every 60 mins

thanks for your helps


Solution

  • i found the easiest way(maybe). just create a custom middleware extending ThrottleRequests.

    php artisan make:middleware ThrottleById
    

    Http\middleware\ThrottleById.php.

    <?php
    namespace App\Http\Middleware;
    use Illuminate\Routing\Middleware\ThrottleRequests;
    class ThrottleById extends ThrottleRequests
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
         * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
         */
        protected function resolveRequestSignature($request)
        {
            $token = $request->route()->parameter('id'); 
            return $token;
        }
    }
    

    this function creates uique signature for each url if id parameter of route is different then just add this middleware to kernel.php same as part 3 & 4 in https://stackoverflow.com/a/75869783/9241751

    thanks to Balaji Kandasamy