Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do filter for products (laravel)

Tags:

php

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?

like image 866
Alexxosipov Avatar asked Jan 08 '18 20:01

Alexxosipov


1 Answers

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);
like image 79
Alexey Mezenin Avatar answered Nov 13 '22 20:11

Alexey Mezenin