简体   繁体   English

Laravel 资源收集 Rest Api 查询过滤器

[英]Laravel Resource Collection Rest Api Query Filter

I would like to add query params to my rest api.我想将查询参数添加到我的 rest api。 I created that in Resource Collections and now I cant find a way to add this functionality.我在资源 Collections 中创建了它,现在我找不到添加此功能的方法。 Every tutorial is for other ways of creating api.每个教程都针对创建 api 的其他方法。 I would like to add to endpoint /api/v1/product filtering by product code something like this: /api/v1/product?product_code=0208588343711.我想通过产品代码添加到端点 /api/v1/product 过滤,如下所示:/api/v1/product?product_code=0208588343711。 This is my code这是我的代码

Product Controller:产品 Controller:

public function index(): ProductCollection
{
    return new ProductCollection(Product::paginate());
}

ProductCollection产品系列

class ProductCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

If someone need a answer so I did this in this way:如果有人需要答案,那么我就是这样做的:

public function index(): ProductCollection
    {
        if (request()->input('product_code')){
            return new ProductCollection(Product::where('product_code', 'LIKE', request()->input('product_code'))->get());
        }
        return new ProductCollection(Product::paginate());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM