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

<?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.