简体   繁体   English

有没有更简单的方法来过滤Laravel资源集合中的列?

[英]Is there an easier way to filter columns in a Laravel Resource Collection?

<?php

namespace App\Http\Resources\Moderate;

use Illuminate\Http\Resources\Json\ResourceCollection;

class MoveSearchCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        foreach($this->collection as $key => $value) {
            $this->collection[$key] = $this->collection[$key]->only(['id', 'name']);
        }

        return [
            'data' => $this->collection,
        ];
    }
}

I have the collection above and can filter it, but is there an easier way to only include certain fields? 我上面有集合,可以对其进行过滤,但是有没有更简单的方法来仅包含某些字段?

There sure is, instead of collecting the model, collect a singular resource. 当然,不是收集模型,而是收集单个资源。 If you look here it will show you how to first make a singular resource and then collect it with your resource collection. 如果您在此处查看 ,它将向您展示如何首先制作单个资源,然后再与资源集合一起收集它。 In the singular resource you can specify any columns or transformations on those columns. 在单个资源中,您可以指定任何列或这些列上的转换。

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

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