# How to Use Rate Limiter in Laravel: A Quick Guide

Rate limiting is a crucial feature in web applications to control the number of requests a user can make to the server within a specific timeframe. This helps protect your application from abuse, such as brute force attacks and ensures fair usage of your resources. Read [this](https://blog.bytebytego.com/p/rate-limiting-fundamentals) if you need more information.

In this post, we'll dive deep into Laravel's rate-limiting capabilities and how to implement them in your application.

### Using middleware

```php
//routes/web/php
Route::get('/hello', function () {
    return response()
        ->json([
            'version' => '1.0.0',
            'latest_update' => '2022-01-01',
            'data' => 'Hello World!'
        ]);
})->middleware(['throttle:hello']);
```

Define Rate Limits in the `AppServiceProvider.php`

```php
    
// app/providers/AppServiceProvider.php
/**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        RateLimiter::for('hello', function ($request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
```

### How it works?

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1721702789689/24216a97-3fe0-498b-9b58-593f11feb6ff.gif align="center")

### Manually Incrementing Attempts

Check it out from the Laravel 11 resource from [here](https://laravel.com/docs/11.x/rate-limiting#manually-incrementing-attempts).

```php
Route::get('/create-transcript', function (Request $request) {
    if (RateLimiter::tooManyAttempts(
        key: 'transcript:' . $request->ip(),
        maxAttempts: 5
    )) {
        return 'Too many attempts';
    }

    echo 'Transcript created';
    RateLimiter::increment('transcript:' . $request->ip(), amount: 5);
});
```

%[https://www.youtube.com/watch?v=5YlJ8DllTFw]
