Kritim Yantra
Jun 25, 2025
“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.
Let’s say you have 1,000 blog posts. Your API user might want to:
Adding filtering and sorting gives users control and speed.
Let’s work with a Post
model that has these fields:
title
(string)content
(text)author_id
(foreign key)created_at
(timestamp)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));
}
Here are some examples of how users can now interact with your API:
GET /api/posts?search=laravel
GET /api/posts?author_id=3
GET /api/posts?sort_by=title&order=asc
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
To avoid invalid queries, you can add validation like:
$request->validate([
'sort_by' => 'in:title,created_at',
'order' => 'in:asc,desc',
]);
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);
}
Use Postman or Thunder Client and try:
💡 You’ll instantly see how powerful and flexible your API becomes.
where like
where
conditionsorderBy()
Try implementing:
category
then title
)whereHas
)No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google