Laravel - specify fields returned for collection resource

Viewed 296

I have a collection resource like this:

class VehicleCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
        ];
    }
}

And I call this, for example:

    public function index()
    {
        $vehicles = Vehicle::where('id', '>', 0);

        $collection = new VehicleCollection($vehicles->paginate(10));

        return $collection->preserveQuery();
    }

It's important I preserve the pagination query, which is why I didn't use VechicleResource - it doesn't have the option to preserveQuery().

The above works fine but it returns too many fields. For example my Vehicle table has a model_name and a rating column. How can I only return the model_name (or specify which fields I do return) for each model in the response here?

1 Answers

You can use VechicleResource::collection() which return AnonymousResourceCollection and AnonymousResourceCollection extends ResourceCollection, so you can call preserveQuery(). Then you can pick/specify which field you want to send in VechicleResource.

public function toArray($request)
{
    return [
        'data' => VechicleResource::collection($this->collection),
    ];
}
Related