fractal
fractal copied to clipboard
Setting up a custom serializer for just one response
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!
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 :)
HI, @yuloh THe solution worked magic.
Nice.
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.