【问题标题】:How to do filter for products (laravel)如何对产品进行过滤(laravel)
【发布时间】:2025-12-01 11:35:02
【问题描述】:

我做网店。我有 3 个页面,其中产品的过滤器相似 - 目录页面、父类别页面和子类别页面

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

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

控制器中的代码:

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

型号:

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;
    }

但是如何正确地做呢?如何在控制器代码中传递当前$products

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以创建一个local scope。比如:

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

    然后使用它:

    Product::filter()->paginate(20);
    

    【讨论】:

    • 谢谢!我应该从控制器传递相同功能的请求参数吗?或者我应该如何获取 $request 变量?
    • @Alexxosipov 你可以使用request() helper,就像我展示的那样。
    • 我已经在我喜欢的 laravel 电子商务中实现了这个功能,看看这里。 github.com/avored/laravel-ecommerce
    【解决方案2】:

    最近不得不做这样的事情,这是我的整个ProductsController.php 文件: `

             <?php
             namespace App\Http\Controllers;
             use Illuminate\Http\Request;
             use App\Product;
    
            class ProductsController extends Controller
            {
                public function index(Request $request)
                {
                    $products = Product::get();
    
                    if ($request->type) {
                        $products = $products->whereIn('type', $request->type);
                    }
            
                    if ($request->gender) {
                      $products = $products->whereIn('gender', $request->gender);
                    }
    
                   return $products;
    

    `

    您可以根据需要继续添加和过滤,这对我来说就像一个魅力,请注意我使用了whereIn(),因为我请求的数据是以数组的形式输入的,希望这会有所帮助。

    【讨论】:

    • 您正在抢购所有产品。如果你有很多产品,你会最大化内存。
    • 答案的重点是解释whereIn 方法的用法,但如果这让你很困扰,我已经解决了:)