flugg / laravel-responder

A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.
MIT License
862 stars 86 forks source link

Collection Transformers #148

Closed hendrikheil closed 1 year ago

hendrikheil commented 4 years ago

Hi there! Is it possible to map a custom collection to a transformer? Say I pass the success method a collection like Product::all() would return, I would love to be able to transform it differently than a single Product. Personally, most of the time when I pass it a collection I don't want to include all fields, so there is less data to be sent over. Of course just mapping to Illuminate\Support\Collection would be quite useless. But how about something that extends Collection. Like you can do with newCollection on the model.

Does this make sense to add? Or is there just a simpler way to achieve what I am trying to do?

For now I am just passing it the transformer explicitly like this:

    public function index()
    {
        return $this->success(
            QueryBuilder::for(Product::class)->get(),
            ProductCollectionTransformer::class
        );
    }
flugg commented 4 years ago

Hi, passing the transformer explicitly if you have a different transformer for collections is the suggested approach at the moment. You may also look at the only method if you want to filter the response to only include certain fields without having a dedicated transformer for it.

I may also share that a new major version is in the making which replaces Fractal transformers for Laravel's own API resources. This might make what you want to do more streamlined.