Skip to content

Instantly share code, notes, and snippets.

@Shaz3e
Last active July 14, 2024 21:06
Show Gist options
  • Save Shaz3e/47b72d9284c1d617450ebac02933f816 to your computer and use it in GitHub Desktop.
Save Shaz3e/47b72d9284c1d617450ebac02933f816 to your computer and use it in GitHub Desktop.
Rate Limit in Laravel
<?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());
});
}
}
<?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