When building something in the laravel framework, your application might require the ability to mutate eloquent query as well as filtering query results based on the user’s request parameters.
This tutorial will demonstrate the process of filtering query results using pipelines while keeping your code clean and readable.
Pipeline is a design pattern in OOP specifically designed for handling complex mutation of an object where the object is passed through each task (such as passing a pipe) and returns the final transformed object after executing all tasks.
In other words, the laravel pipeline breaks down the huge complex processes of manipulating objects into smaller individual pieces that are responsible for processing and passing data to the next step. As a result, the code becomes easier to maintain and reusable.
Let’s imagine a situation where we are not aware of pipelines, we would normally consider setting up a controller and filter query using conventional if statement.
class PostController
{
public function index(Request $request)
{
$query = Post::query();
if ($request->has('status')) {
$query->where('status', $request->status);
}
if ($request->has('orderBy')) {
$query->orderBy('created_at, $request->orderBy);
}
// And probably all other filters
$posts = $query->get();
return view('post.index', compact('posts'));
}
}
Although this approach might do the job, this will get messy pretty quickly if you have longer multiple conditions.
#laravel #php #web-development