Let’s explore a handy tip for adding extra metadata to the top level of your API responses.
Assume you have a resource that returns the following data:
{
"data": {
"name": "Mahmoud Ramadan",
"role": "Software Engineer"
}
}
Now, let's attach additional data to the root of the response using the additional
method:
/**
* Adds extra metadata using the "additional" method.
*
* @return \Illuminate\Http\Resources\Json\JsonResource
*/
public function addExtraMetadata()
{
return FooResource::make(Baz::first())
->additional([
'website' => 'https://portfolio.mmramadan.com',
]);
}
This will produce the following response:
{
"data": {
"name": "Mahmoud Ramadan",
"role": "Software Engineer"
},
"website": "https://portfolio.mmramadan.com"
}
For more details, refer to the official documentation.
You can also check out the with method, which does the same thing.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.