Laravel: Rate-Limit API Routes with Throttle
Protect your Laravel API from abuse with the built-in throttle middleware — limit requests per minute per user or IP.
Find slow queries in Laravel without guessing — log every query over 500 ms with its SQL, bindings and time.
23 lines · Updated Nov 26, 2026
namespace App\Providers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
if (! config('app.debug')) {
return;
}
DB::listen(function ($query) {
if ($query->time < 500) {
return;
}
Log::warning('Slow query detected', [
'sql' => $query->sql,
'bindings' => $query->bindings,
'time_ms' => $query->time,
]);
});
}
}
"The dashboard is slow" is the most common complaint in any Laravel application, and the cause is almost always one or two database queries. Instead of guessing, this snippet listens to every query Laravel runs and writes the slow ones — with their SQL, bindings and execution time — to your log. Leave it running in production and the slow queries find you.
boot() method of AppServiceProvider.daily log channel so log files rotate.storage/logs for "slow query" entries.EXPLAIN. A full table scan (type: ALL) usually means a missing index on a WHERE, JOIN or ORDER BY column.with().php artisan optimize:clear.Is it safe in production? Yes — the cost is tiny, and production is where real slow queries appear.
Related: System design basics · Deploy Laravel on a VPS
Open app/Providers/AppServiceProvider.php and put the code inside the boot() method. It only runs when APP_DEBUG is true, so your production logs stay clean — turn debug on in your local .env (APP_DEBUG=true), load the slow page, then read the log with php artisan pail or by opening storage/logs/laravel.log and searching for "Slow query detected". Works with Laravel 11, 12 and 13 on PHP 8.2 and newer.
Share this snippet
Protect your Laravel API from abuse with the built-in throttle middleware — limit requests per minute per user or IP.
Generate a sitemap.xml from your database in Laravel — always up to date, no file to maintain by hand.
Send WhatsApp messages from Laravel through a provider API — order updates, OTPs and alerts in a few lines.