如何做产品过滤器(laravel)

Ale*_*pov 3 php laravel

我在网上商店。我有3个页面,其中产品过滤条件相似-目录页面,父类别页面和子类别页面

site/catalog/  // catalogController@index
site/catalog/parentCategory/childrenCategory //childrenCategoryController@index
site/catalog/parentCategory //parentCategoryController@index
Run Code Online (Sandbox Code Playgroud)

过滤器是通过get请求制作的,例如:site/catalog?price_from=1&price_to=9999&color=red。如何使这个过滤器成为一个单独的功能?在产品模型中做到这一点会很好吗?以及如何使用它?我认为这应该是一个接受2个参数(请求参数和当前查询模型)并返回的函数$this

控制器中的代码:

$products = Product::filter($products, $request)->paginate(20);     
Run Code Online (Sandbox Code Playgroud)

模型:

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;
    }
Run Code Online (Sandbox Code Playgroud)

但是怎么做对呢?如何$products在控制器代码中传递电流?

Ale*_*nin 5

您可以创建本地范围。就像是:

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

    return $q;
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

Product::filter()->paginate(20);
Run Code Online (Sandbox Code Playgroud)