matthewerskine/request-filters

Laravel 请求过滤助手。

1.0.0 2018-05-01 10:36 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:41:56 UTC


README

此包用于允许使用简单的请求参数快速动态地对基于eloquent的模型进行过滤。非常适合后端API!

配置

要开始在Laravel中使用此包,您首先需要创建一个宏,用于定义request()->filter()方法,如下所示

use MatthewErskine\RequestFilters\RequestFilters;

request()->macro('filters', function() {
    return RequestFilters::getFilterCollection(
        // Use the 'filters' query param.
        request()->query('filters')
    );
});

注意:对于Lumen应用,您需要一个辅助文件来定义request()方法,因为这不是默认可用的。

现在,您可以在任何仓库中开始根据在filters查询参数中提供的策略和参数信息对模型的结果进行过滤

public function getFood()
{
    return request()->filters()->apply(
        DB::table('food')
    );
}

现在,我们可以提供一个包含如何过滤我们食品的JSON策略的base_64编码字符串。例如

[
    {
        "strategy": "where",
        "parameters": [
            "calories",
            ">",
            100
        ]
    },
    {
        "strategy": "whereIn",
        "parameters": [
            "food_type",
            "('fried', 'baked')"
        ]
    }
]