简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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