Filtering and Sorting API Results in Laravel 12: The Smart Way
“Imagine browsing an online store with no way to search or sort — total chaos, right?”
Users expect fast, relevant, and organized data — whether it’s searching for posts, filtering by category, or sorting by price or date. Thankfully, Laravel 12 makes it easy to add filtering and sorting to your API endpoints.
In this blog post, you'll learn how to build flexible filtering and sorting logic into your Laravel 12 API step by step.
🧠 Why Filtering and Sorting Matter
Let’s say you have 1,000 blog posts. Your API user might want to:
- 🔎 Search by title or keyword
- 🗂️ Filter by author or category
- 📅 Sort by newest or oldest
- 🔼 Order alphabetically
Adding filtering and sorting gives users control and speed.
📁 Use Case: Blog Post API
Let’s work with a Post model that has these fields:
title(string)content(text)author_id(foreign key)created_at(timestamp)
🛠️ Step 1: Add Filtering Logic in the Controller
Let’s enhance your PostController@index() method.
public function index(Request $request)
{
$query = Post::query();
// 🔍 Filter by title keyword
if ($request->has('search')) {
$query->where('title', 'like', '%' . $request->search . '%');
}
// 🧑 Filter by author ID
if ($request->has('author_id')) {
$query->where('author_id', $request->author_id);
}
// ⬆️⬇️ Sorting
if ($request->has('sort_by') && $request->has('order')) {
$query->orderBy($request->sort_by, $request->order);
} else {
$query->latest(); // default sorting
}
// 📦 Paginate and return
return PostResource::collection($query->paginate(10));
}
💡 Example API Requests
Here are some examples of how users can now interact with your API:
1. Search by title
GET /api/posts?search=laravel
2. Filter by author
GET /api/posts?author_id=3
3. Sort by title (A-Z)
GET /api/posts?sort_by=title&order=asc
4. Sort by creation date (newest first)
GET /api/posts?sort_by=created_at&order=desc
You can also combine filters and sorting:
GET /api/posts?search=api&author_id=5&sort_by=title&order=asc
🧰 Step 2: Optional – Validate Filter Inputs
To avoid invalid queries, you can add validation like:
$request->validate([
'sort_by' => 'in:title,created_at',
'order' => 'in:asc,desc',
]);
🔐 Step 3: Protect Sensitive Filters
If you're filtering by fields like is_admin or user_id, always make sure to add proper authorization checks:
if ($request->has('user_id') && auth()->user()->isAdmin()) {
$query->where('user_id', $request->user_id);
}
🧪 Testing Filters and Sorting
Use Postman or Thunder Client and try:
- Searching for keywords
- Filtering by author
- Sorting by different fields
💡 You’ll instantly see how powerful and flexible your API becomes.
🧠 Summary: Filtering & Sorting in Laravel 12
- 🔍 Add smart search with
where like - 🧑 Use filters with
whereconditions - ⬆️⬇️ Add sorting using
orderBy() - ✅ Always validate and secure input
🚀 Bonus Challenge
Try implementing:
- ✅ Multi-field sorting (e.g., sort by
categorythentitle) - ✅ Filtering by related models (e.g., author name via
whereHas) - ✅ Range filters (e.g., date range or price range)
Projects related to this guide
Use the concepts from this article in practical source-code projects.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure...
Python Flask Blog Project with Admin Panel
Are you ready to launch a powerful, modern, and fully customizable blog? Look no further! Introducing the Flask-...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes pr...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.