Laravel Throttle - A rate limiter for Laravel

Overview

Laravel Throttle

Laravel Throttle was created by, and is maintained by Graham Campbell, and is a rate limiter for Laravel. Feel free to check out the change log, releases, security policy, license, code of conduct, and contribution guidelines.

Banner

Build Status StyleCI Status Software License Packagist Downloads Latest Version

Installation

Laravel Throttle requires PHP 7.2-8.1. This particular version supports Laravel 6-9.

Throttle L5.1 L5.2 L5.3 L5.4 L5.5 L5.6 L5.7 L5.8 L6 L7 L8 L9
4.1
5.3
6.0
7.5
8.2

To get the latest version, simply require the project using Composer:

$ composer require "graham-campbell/throttle:^8.2"

Once installed, if you are not using automatic package discovery, then you need to register the GrahamCampbell\Throttle\ThrottleServiceProvider service provider in your config/app.php.

You can also optionally alias our facade:

        'Throttle' => GrahamCampbell\Throttle\Facades\Throttle::class,

Configuration

Laravel Throttle supports optional configuration.

To get started, you'll need to publish all vendor assets:

$ php artisan vendor:publish

This will create a config/throttle.php file in your app that you can modify to set your configuration. Also, make sure you check for changes to the original config file in this package between releases.

There is one config option:

Cache Driver

This option ('driver') defines the cache driver to be used. It may be the name of any driver set in config/cache.php. Setting it to null will use the driver you have set as default in config/cache.php. The default value for this setting is null.

Usage

Throttle

This is the class of most interest. It is bound to the ioc container as 'throttle' and can be accessed using the Facades\Throttle facade. There are six public methods of interest.

The 'get' method will create a new throttler class (a class that implements Throttler\ThrottlerInterface) from the 1-3 parameters that you pass to it. The first parameter is required and must either an instance of \Illuminate\Http\Request, or an associative array with two keys ('ip' should be the ip address of the user you wish to throttle and 'route' should be the full url you wish to throttle, but actually, for advanced usage, may be any unique key you choose). The second parameter is optional and should be an int which represents the maximum number of hits that are allowed before the user hits the limit. The third and final parameter should be an int that represents the time the user must wait after going over the limit before the hit count will be reset to zero. Under the hood this method will be calling the make method on a throttler factory class (a class that implements Factories\FactoryInterface).

The other 5 methods all accept the same parameters as the get method. What happens here is we dynamically create a throttler class (or we automatically reuse an instance we already created), and then we call the method on it with no parameters. These 5 methods are 'attempt', 'hit', 'clear', 'count', and 'check'. They are all documented bellow.

Facades\Throttle

This facade will dynamically pass static method calls to the 'throttle' object in the ioc container which by default is the Throttle class.

Throttler\ThrottlerInterface

This interface defines the public methods a throttler class must implement. All 5 methods here accept no parameters.

The 'attempt' method will hit the throttle (increment the hit count), and then will return a boolean representing whether or not the hit limit has been exceeded.

The 'hit' method will hit the throttle (increment the hit count), and then will return $this so you can make another method call if you so choose.

The 'clear' method will clear the throttle (set the hit count to zero), and then will return $this so you can make another method call if you so choose.

The 'count' method will return the number of hits to the throttle.

The 'check' method will return a boolean representing whether or not the hit limit has been exceeded.

Throttler\CacheThrottler

This class implements Throttler\ThrottlerInterface completely. This is the only throttler implementation shipped with this package, and in created by the Factories\CacheFactory class. Note that this class also implements PHP's Countable interface.

Factories\FactoryInterface

This interface defines the public methods a throttler factory class must implement. Such a class must only implement one method.

The 'make' method will create a new throttler class (a class that implements Throttler\ThrottlerInterface) from data object you pass to it. This documentation of an internal interface is included for advanced users who may wish to write their own factory classes to make their own custom throttler classes.

Factories\CacheFactory

This class implements Factories\FactoryInterface completely. This is the only throttler implementation shipped with this package, and is responsible for creating the Factories\CacheFactory class. This class is only intended for internal use by the Throttle class.

Http\Middleware\ThrottleMiddleware

You may put the GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware middleware in front of your routes to throttle them. The middleware can take up to two parameters. The two parameters are limit and time. It may be useful for you to take a look at the source for this, read the tests, or check out Laravel's documentation if you need to.

ThrottleServiceProvider

This class contains no public methods of interest. This class should be added to the providers array in config/app.php. This class will setup ioc bindings.

Real Examples

Here you can see an example of just how simple this package is to use.

Our first example will be a super simple usage of our default middleware. This will setup a middleware for that url with a limit of 10 hits and a retention time of 1 hour.

use Illuminate\Support\Facades\Route;

Route::get('foo', ['middleware' => 'GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware', function () {
    return 'Why herro there!';
}]);

What if we want custom limits? Easy! Laravel allows us to pass parameters to a middleware. This will setup a middleware for that url with a limit of 50 hits and a retention time of 30 mins.

use Illuminate\Support\Facades\Route;

Route::get('foo', ['middleware' => 'GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware:50,30', function () {
    return 'Why herro there!';
}]);

What if we don't want to use the default middleware provided with this package? Well, that's easy too.

check()); // we implement Countable var_dump(count($throttler)); // there are a few more functions available // please see the previous documentation">
use GrahamCampbell\Throttle\Facades\Throttle;
use Illuminate\Support\Facades\Request;

// now let's get a throttler object for that request
// we'll use the same config as in the previous example
// note that only the first parameter is "required"
$throttler = Throttle::get(Request::instance(), 50, 30);

// let's check if we've gone over the limit
var_dump($throttler->check());

// we implement Countable
var_dump(count($throttler));

// there are a few more functions available
// please see the previous documentation

Also note that you can call methods straight on the factory instead of calling the get method.

use GrahamCampbell\Throttle\Facades\Throttle;
use Illuminate\Support\Facades\Request;

$request = Request::instance();

// the attempt function will hit the throttle, then return check
var_dump(Throttle::attempt($request));

// so this is the same as writing
var_dump(Throttle::hit($request)->check());

// and, of course, the same as
var_dump(Throttle::get($request)->attempt());
Further Information

There are other classes in this package that are not documented here (such as the transformers). This is because they are not intended for public use and are used internally by this package.

Security

If you discover a security vulnerability within this package, please send an email to [email protected]. All security vulnerabilities will be promptly addressed. You may view our full security policy here.

License

Laravel Throttle is licensed under The MIT License (MIT).

For Enterprise

Available as part of the Tidelift Subscription

The maintainers of graham-campbell/throttle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Comments
  • How do i get this up and running in Lumen?

    How do i get this up and running in Lumen?

    I've added the package and done an composer update. Added into my routeMiddleware in app.php i.e

    $app->routeMiddleware([ 'Throttle' => 'GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware', ]);

    And added it to my route: $app->get('api','App\Http\Controllers\ApiController@index', ['middleware' => 'Throttle:1,1']);

    But nothing seems to happen. I suspect it's got to do with the vendor:publish command which doesn't exist in Lumen. No errors are thrown.

    Any chance of some tips on how to get this up and running?

    opened by jimmyjamieson 30
  • You cannot serialize or unserialize PDO instances

    You cannot serialize or unserialize PDO instances

    Trying out the project for the first time, so my apologies if these are known issues and this goes beyond the scope of what you're trying to do with it.

    If I instantiate a throttle with the following

    $request = Request::instance();
    Throttle::get($request, 5, 10);
    

    Laravel fails with the following error.

    You cannot serialize or unserialize PDO instances

    public function get($data, $limit = 10, $time = 60)
    {
        $key = md5(serialize($data).$limit.$time);
    

    Our application is configured to use the database session handler, and it seems the attempts to serialize a request object that contains this handler fails.

    bug enhancement 
    opened by astormcupdx 12
  • Throttle::attempt() goes over limit before returning

    Throttle::attempt() goes over limit before returning "false"

    With the following code:

    if (!Throttle::attempt($request, 5)) {
        throw new Exception('Over limit');
    }
    
    doSomething();
    

    The exception is not thrown on the sixth attempt as expected, but on the seventh. The issue seems related to issue #6.

    opened by dcro 11
  • Composer Laravel 4.2

    Composer Laravel 4.2

    Hello GrahamCampbell,

    Is this package already compatible with Laravel 4.2?

    Problem 1 - graham-campbell/throttle v0.2.0-alpha requires laravel/framework 4.1.* -> no matching package found. - graham-campbell/throttle v0.2.0-alpha requires laravel/framework 4.1.* -> no matching package found. - Installation request for graham-campbell/throttle 0.2.*@alpha -> satisfiable by graham-campbell/throttle[v0.2.0-alpha].

    question 
    opened by MarkVink 11
  • Throttle check function always returns true

    Throttle check function always returns true

    I have the following in my Route file,

    use GrahamCampbell\Throttle\Facades\Throttle;
    use Illuminate\Support\Facades\Request;
    
    Route::get('throttle-check', function(){
        $throttler = Throttle::get(Request::instance(), 5, 3);
        // let's check if we've gone over the limit
        var_dump($throttler->check());
        // count
        var_dump(count($throttler));
    });
    

    When I run this, it always returns bool(true) int(0) Even on the first run.

    Am I doing something wrong or is it the package?

    I am using the latest version (5.1.0) on Laravel 5.1.24 (LTS)

    opened by r-a-o 9
  • Added ttl method

    Added ttl method

    Hi there 👋 I've added a method to check for the end of the current duration. This way you will be able to add all standard rate-limit headers (X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset). It would be great if each Laravel cache implementation handles such functionality, but for now this is the best we can do. Hopefully you like it 😄

    opened by robinvdvleuten 8
  • Throttle based on a JWT token instead of IP address

    Throttle based on a JWT token instead of IP address

    I am using JWT token in header to authorize users. So I can uniquely identify a particular user with the token. Can I use this JWT token instead of IP address to identify a user. Multiple users behind a Proxy server can cause problems with IP address filtering. If I can uniquely identify a user i can set exact limits like 3 login attempts/hr. How can i do this?

    opened by rohitnaidu19 8
  • Crated TransformerFactoryInterface, and now Throttle constructor acce…

    Crated TransformerFactoryInterface, and now Throttle constructor acce…

    …pt Interface instead of TransformerFactory

    TransformerFactoryInterface is created and in case we want to create another TransformerFactory and inject it into Throttle class.

    Current TransformerFactory can only return ArrayTransformer or RequestTransformer, and it is not replacable.

    Another approach could be to create a strategy and allow TransformerFactory to return any TransformerInterface via container.

    We can discuss what is a better approach to make Transformers replaceable.

    If you ask me "Why we want another Transformers", I could say that in some cases we do not want to count by IP address, we might want to track users by own id. At the moment both transformers are able to create Data object based on IP address and route.

    This is just one step to make this package more extensible.

    opened by Djuki 7
  • not working for me

    not working for me

    i am using this code

    use GrahamCampbell\Throttle\Facades\Throttle;
    use Illuminate\Support\Facades\Request;
    
    $throttler = Throttle::get(Request::instance(), 10, 1);
    
    // let's check if we've gone over the limit
            var_dump($throttler->check());
    
    // we implement Countable
            var_dump(count($throttler));
    

    but i am not getting count and true or false for check() method. and also i am using cache with file

    opened by charanjeet5ingh 7
  • Keys do not expire because store::put() extends the key expire time

    Keys do not expire because store::put() extends the key expire time

    Hi,

    I have a middleware set to 100 hits per 2 minutes. If someone requests insane amount of api calls he'll get rate limited. All OK at this point.

    If normal users do an api requests (for example) once per 30 seconds, they'll get banned also. See why:

    When $throttle->attempt() checks if user is banned or not it calls hit() which increments the counter. Code

    The Store::put() calls MemcacheStore::put() and that one does memcached::set() Code

    Here's the problem: Memcached::set() overwrites an object hence extending its time lib info. So we increment the counter and this counter is counting hits that happened long way back than 2 minutes.

    Example: 1st hit at 10:00:00 ... key value is 1, expire time is 10:02:00 2nd hit at 10.00.30 ... key value is 2, expire time is moved to 10:02:30 due to Memcaches:set()
    3rd hit at 10:01:00 ... key value is 3, expire time is 10:03:00 ... 10th hit is at 10:05:00 ... key value is 10, expire time is again moved forward to 10:07:00

    Slowly, user will get banned, even thou he was under the rate limit set in middleware.

    Any thought on this?

    opened by RatkoR 7
  • does not have a method 'tags'

    does not have a method 'tags'

    Hi, I'm using the Laravel Framework version 4.2.11.

    And I have this error message :

    call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Cache\DatabaseStore' does not have a method 'tags'
    

    I have switched to file but I have the same :

    call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Cache\FileStore' does not have a method 'tags'
    

    Any idea ?

    opened by sirsquall 7
  • error in decimal usage with redis

    error in decimal usage with redis

    I get an error when I set the time to seconds.

    usage: ->middleware('ThrottleMiddleware:10,0.1');

    error: ERR invalid expire time in setex at /var/www/vendor/predis/predis/src/Client.php:370)

    opened by arlong87 0
Releases(v9.0.0)
Owner
Graham Campbell
OSS Maintainer | Laravel | StyleCI
Graham Campbell
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

Laravel Lang 6.9k Jan 2, 2023
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.

What is laravel charts? Charts is a Laravel library used to create Charts using Chartisan. Chartisan does already have a PHP adapter. However, this li

Erik C. Forés 31 Dec 18, 2022
Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster.

Laravel Kickstart What is Laravel Kickstart? Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster. It com

Sam Rapaport 46 Oct 1, 2022
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

null 9 Dec 14, 2022
Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application.

Laravel Segment Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application. Installation You can install the pac

Octohook 13 May 16, 2022
Laravel Sanctum support for Laravel Lighthouse

Lighthouse Sanctum Add Laravel Sanctum support to Lighthouse Requirements Installation Usage Login Logout Register Email Verification Forgot Password

Daniël de Wit 43 Dec 21, 2022
Bring Laravel 8's cursor pagination to Laravel 6, 7

Laravel Cursor Paginate for laravel 6,7 Installation You can install the package via composer: composer require vanthao03596/laravel-cursor-paginate U

Pham Thao 9 Nov 10, 2022
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Ollie Codes 19 Jul 5, 2021
A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

Adnane Kadri 49 Jun 22, 2022
Jetstrap is a lightweight laravel 8 package that focuses on the VIEW side of Jetstream / Breeze package installed in your Laravel application

A Laravel 8 package to easily switch TailwindCSS resources generated by Laravel Jetstream and Breeze to Bootstrap 4.

null 686 Dec 28, 2022
Laravel Jetstream is a beautifully designed application scaffolding for Laravel.

Laravel Jetstream is a beautifully designed application scaffolding for Laravel. Jetstream provides the perfect starting point for your next Laravel application and includes login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management.

The Laravel Framework 3.5k Jan 8, 2023
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

Laravel Larex Translate Laravel Apps from a CSV File Laravel Larex lets you translate your whole Laravel application from a single CSV file. You can i

Luca Patera 68 Dec 12, 2022
A Laravel package that adds a simple image functionality to any Laravel model

Laraimage A Laravel package that adds a simple image functionality to any Laravel model Introduction Laraimage served four use cases when using images

Hussein Feras 52 Jul 17, 2022
A Laravel extension for using a laravel application on a multi domain setting

Laravel Multi Domain An extension for using Laravel in a multi domain setting Description This package allows a single Laravel installation to work wi

null 658 Jan 6, 2023
Example of using abrouter/abrouter-laravel-bridge in Laravel

ABRouter Laravel Example It's a example of using (ABRouter Laravel Client)[https://github.com/abrouter/abrouter-laravel-bridge] Set up locally First o

ABRouter 1 Oct 14, 2021
Laravel router extension to easily use Laravel's paginator without the query string

?? THIS PACKAGE HAS BEEN ABANDONED ?? We don't use this package anymore in our own projects and cannot justify the time needed to maintain it anymore.

Spatie 307 Sep 23, 2022
Laravel application project as Sheina Online Store backend to be built with Laravel and VueJS

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Boas Aditya Christian 1 Jan 11, 2022
Postgis extensions for laravel. Aims to make it easy to work with geometries from laravel models.

Laravel Wrapper for PostgreSQL's Geo-Extension Postgis Features Work with geometry classes instead of arrays. $model->myPoint = new Point(1,2); //lat

Max 340 Jan 6, 2023
laravel - Potion is a pure PHP asset manager for Laravel 5 based off of Assetic.

laravel-potion Potion is a pure PHP asset manager for Laravel based off of Assetic. Description Laravel 5 comes with a great asset manager called Elix

Matthew R. Miller 61 Mar 1, 2022