Advanced Filtering: Building Search + Sort + Pagination Correctly
Build reliable search endpoints that support filters, sorting, and pagination without messy controller code.
Real applications need flexible filtering: - search by keyword - filter by status - date ranges - sort newest/oldest - paginate ## Example endpoint ```php public function index(Request $request) { $q = Post::query()->with('user'); if ($request->filled('status')) { $q->where('status', $request->status); } if ($request->filled('search')) { $search = $request->search; $q->where(function ($sub) use ($search) { $sub->where('title', 'like', "%$search%") ->orWhere('body', 'like', "%$search%"); }); } $sort = $request->get('sort', 'desc'); $q->orderBy('created_at', $sort); return $q->paginate(10); } ``` ## Graph: filter pipeline ```mermaid flowchart LR A[Request Params] --> B[Query Builder] B --> C[Filters Applied] C --> D[Sort Applied] D --> E[Pagination] E --> F[Response] ``` In the next tutorial, we will discuss database design for many-to-many relationships.