Use Pipeline in Laravel for querry filter functionality

Tram Ho

I. Introduction:

Basically, the Pipeline in Laravel will take the Request and pass it through the global middewares first (for example, CheckForMaintenanceMode, TrimStrings, ValidatePostSize …) then the route middlewares and controller middlewares. Eventually the request will be dispatched to the router for a Illuminate Http Response.

When I learn about Request Lifecycle on the Kernel, I will encounter this code (Refer here ) using Pipeline with the above purpose:

Using Pipeline in Laravel you can dynamically pass an object across multiple classes in order, to perform a certain series of tasks (such as passing pipes) and eventually return a result when done. the whole task has been executed. Today we will implement Pipeline in laravel to perform the filter functionality.

II. What is Pipeline Design Pattern?

Pipeline Design Pattern is where data is passed through a series of tasks or stages. Pipeline works like an assembly line where data is processed and then passed on to the next stage.

Complex processes we can break down into single tasks. Each single task is highly reusable. Break down a large process into smaller tasks that process data, and then move that data to the next step until you get the results you want.

Hic, in theory, we think of a certain product filter function with the purpose that after filtering by category for example 5 products, we want to continue to filter by color based on the previous result ( 5 products) and finally the results we want. Ok here we will apply Pipeline to implement the function of filtering posts by active field and sorting by title.

Step 1: Create a route to return data:

Step 2: Create Model – Controller – table products:

Step 3: Seed data:

  • Factory:

  • Seed data by Tinker:

Step 4: Setup Model:

Here we will filter by active post and sort the post by title. Create 2 classes to perform the above task: App QueryFilters Active :: class, App QueryFilters Sort :: class

If you have consulted the Pipeline Laravel class you will see the following 3 methods:

You pass the object you want to send through the pipeline.

Next you pass a series of tasks that will process the request, meaning that the request will go through these tasks one after another.

Finally you get the expected results.

Step 4: Setup Controller:

Step 4: Our Custom Class Filter:

  • Each class in the through () method must have a “handle” method to perform certain tasks. We will create an interface for these classes.

  • And the classes that we use to filter will implement this interface:

App QueryFilters Sort :: class

App QueryFilters Active :: class

III. Result :

Share the news now

Source : Viblo