DEV Community

Cover image for Pipeline Pattern in Laravel

Pipeline Pattern in Laravel

Abrar Ahmad on August 07, 2021

PP = Pipeline Pattern Today, we will learn the Pipeline Pattern and how to use it in Laravel. You can read in depth about PP at HERE. PP can be ...
Collapse
 
rabeeaali profile image
Rabeea Ali • Edited

Another approach for this example is:

in PostController

public function index(Request $request)
{
     $posts = Post::query()
            ->postFilter()
            ->get();

     return view('demo', compact('posts'));
}
Enter fullscreen mode Exit fullscreen mode

in Post model

public function scopePostFilter($query)
{
       $query->when(
            request('active'),
            fn ($query) => $query->where('active', request('active'))
        );

        $query->when(
            request('sort'),
            fn ($query) => $query->orderBy('title', request('sort'));
        );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
parminder_kaur_ac7a906959 profile image
parminder kaur

Your approach is specific for only post model. And above Pipeline example in tutorial can be used in multiple contollers.

Collapse
 
rabeeaali profile image
Rabeea Ali

you can make a trait and use it in each model you want

Collapse
 
abrardev99 profile image
Abrar Ahmad

Nice abstractions.

Collapse
 
sluxzer profile image
sluxzer

I Loved it, it's will be so much useful for dynamic repetition too

Collapse
 
rmoskal profile image
Robert Moskal

Certainly pipelines are nice. But in this example they are ruined by having to create two separate modules to implement the filters, rather then to just do it inline.

Collapse
 
abrardev99 profile image
Abrar Ahmad

I think you missed the post conclusion. Any here it is.

It might feel overwhelm to implement Pipelines just for two filters but it will be much clean and beneficial for large number of filter or any other complex implementation.

Collapse
 
abrardev99 profile image
Abrar Ahmad

Example here is just for basic understanding of Pipeline. I won't be implement Pipeline for just two filters.

Collapse
 
sheikhusman545 profile image
sheikhusman545

thankyou for teaching me with the most easiest and simple example

Collapse
 
abrardev99 profile image
Abrar Ahmad

Glad you learn.

Collapse
 
asantana66 profile image
asantana66

I think this is a good approach to code reuse for those about filtering by a common field in tables.
Thanks for the input!!

Collapse
 
henryonsoftware profile image
Henry Bui

I usually use Traits for some filters, but your Pipelines pattern is more clear and that is good approach if we have many filters. Big thanks

Collapse
 
abrardev99 profile image
Abrar Ahmad

Enjoy

Collapse
 
aymenalhattami profile image
Ayman Alhattami

I love it :)