Last active
July 14, 2024 21:06
-
-
Save Shaz3e/47b72d9284c1d617450ebac02933f816 to your computer and use it in GitHub Desktop.
Rate Limit in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use Illuminate\Cache\RateLimiting\Limit; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\RateLimiter; | |
use Illuminate\Support\ServiceProvider; | |
class AppServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Register any application services. | |
*/ | |
public function register(): void | |
{ | |
// | |
} | |
/** | |
* Bootstrap any application services. | |
*/ | |
public function boot(): void | |
{ | |
RateLimiter::for('your_key', function (Request $request) { | |
// return Limit::perMinute(1) | |
// ->by($request->user()?->id ?: $request->ip()); // 1 request per minute per user | |
// Rate Limit by Logged in User vs Normal User | |
// return $request->user() ? | |
// Limit::perMinute(2)->by($request->ip()) : | |
// Limit::perMinute(1)->by($request->ip()); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Support\Facades\Route; | |
Route::get('/your-url', function () { | |
return response() | |
->json([ | |
'data' => 'data will be here' | |
]); | |
})->middleware(['throttle:your_key']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment