How to build a conditional based query in Laravel that gets shaped based on conditional statements before finally being executed.
In this example below checks are made on if the request has values and if so then a where query gets added
$query = Article::query(); if ($request->has('title')) { $query->where('title', 'like', '%' . $request->input('title') . '%'); } if ($request->has('less_than_date')) { $query->whereDate('created_at', '<=', $request->input('less_than_date')); } $query->orderBy('created_at', 'desc'); $articles = $query->get();
Finally the query is executed after being built.