fractal icon indicating copy to clipboard operation
fractal copied to clipboard

Setting up a custom serializer for just one response

Open iamrutvik opened this issue 9 years ago • 3 comments

All I want to do is remove data key from included model response. So I have created a new custom serializer NoDataArraySerilizer.php :

`namespace App\Api\V1\Serializers; use League\Fractal\Serializer\ArraySerializer; class NoDataArraySerializer extends ArraySerializer { public function collection($resourceKey, array $data) { //return ($resourceKey) ? [ $resourceKey => $data ] : $data;

}
public function item($resourceKey, array $data)
{
    //return ($resourceKey) ? [ $resourceKey => $data ] : $data;
}

}`

and in transformer while including, I did something like this :

`public function includeFromPlace(Ride $ride) { return $this->item($ride->fromplace()->where('place_id' ,$ride->from_place_id)->get()->first(), new PlaceTransformer, false, function ($resource, $fractal) { $fractal->setSerializer(new \App\Api\V1\Serializers\NoDataArraySerializer); });

}`

Still it does not remove key. What am i doing wrong? Please help!

iamrutvik avatar Aug 20 '16 08:08 iamrutvik

Hi @iamrutvik,

You should be able to remove the data namespace from includes when merging the includes with the primary resource.

You don't need to change the serializer within your include. Just use something like this serializer and it should work fine:

class CustomSerializer extends DataArraySerializer
{
    public function mergeIncludes($transformedData, $includedData)
    {
        $includedData = array_map(function ($include) {
            return $include['data'];
        }, $includedData);

        return parent::mergeIncludes($transformedData, $includedData);
    }
}

Please let me know and close the issue if that works :)

matt-allan avatar Sep 22 '16 01:09 matt-allan

HI, @yuloh THe solution worked magic.

Nice.

oversimplifyd avatar Sep 14 '17 15:09 oversimplifyd

This issue has been automatically marked as stale because it has not had recent activity. It will be closed after 4 weeks if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 16 '22 06:04 stale[bot]