Skip to content
Advertisement

How to do filter for products (laravel)

I do the online shop. I have 3 pages where filters for products are similar – Catalog page, parent category page and children category page

site/catalog/  // catalogController@index
site/catalog/parentCategory/childrenCategory //childrenCategoryController@index
site/catalog/parentCategory //parentCategoryController@index

The filter is made via get requests, like that: site/catalog?price_from=1&price_to=9999&color=red. How to make this filter into a separate function? Will it be good to make this in a product model? And how to use it? I think it should be a function that accepts 2 params (request params and current query model) and returns $this.

Code in controllers:

$products = Product::filter($products, $request)->paginate(20);     

Model:

public function filter($model, Request $request) {
        if ($request->has('price_from')) {
            $model->where('price', '>', $request->get('price_from'));
        }
        if ($request->has('color')) {
            $model->where('color', '>', $request->get('color'));
        }

        return $model;
    }

But how to do it right? How to pass current $products in controller code?

Advertisement

Answer

You can create a local scope. Something like:

public function scopeFilter($q)
{
    if (request('price_from')) {
        $q->where('price', '>', request('price_from'));
    }
    if (request('color')) {
        $q->where('color', '>', request('color'));
    }

    return $q;
}

Then use it:

Product::filter()->paginate(20);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement