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.
Add one search scope to any Eloquent model and search across several columns with a single method call.
22 lines · Updated Nov 26, 2026
<?php
// In your model, e.g. app/Models/Post.php
public function scopeSearch($query, ?string $term)
{
if (blank($term)) {
return $query;
}
return $query->where(function ($q) use ($term) {
$q->where('title', 'like', "%{$term}%")
->orWhere('body', 'like', "%{$term}%")
->orWhereHas('user', function ($u) use ($term) {
$u->where('name', 'like', "%{$term}%");
});
});
}
// Usage in a controller:
// $posts = Post::search($request->input('q'))
// ->latest()
// ->paginate(15);
Almost every admin panel needs a search box, and copying the same where ... like chain into every controller quickly gets messy. This snippet wraps search in a reusable Eloquent local scope: write the logic once in your model, then call Product::search($term)->paginate() anywhere.
scope that receives the query builder.LIKE conditions across the columns you choose. Grouping them in a closure keeps them from breaking other where conditions such as status = published.LIKE '%term%' search cannot use a normal index, so it slows down on very large tables.term%) add an index on the column.orWhereHas('category', ...) inside the same group.Is it case-insensitive? With MySQL's default collations, yes. On PostgreSQL use ILIKE.
Related: Build a live search with Livewire · Log slow queries
Add the scopeSearch method to your model and change the column names to match your table. Call it from the controller with the search term from the request.
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.