Add Top-Level Data with Resource
Mahmoud Ramadan

Mahmoud Ramadan @mmramadan496

About: Computer Science Geek 🧐 || Software Engineer 👨‍💻 || Digging Code Creator 🚀

Location:
Mansoura, Dakahlia, Egypt
Joined:
Jan 15, 2024

Add Top-Level Data with Resource

Publish Date: Jun 8 '25
0 2

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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',
        ]);
}
Enter fullscreen mode Exit fullscreen mode

This will produce the following response:

{
  "data": {
    "name": "Mahmoud Ramadan",
    "role": "Software Engineer"
  },
  "website": "https://portfolio.mmramadan.com"
}
Enter fullscreen mode Exit fullscreen mode

For more details, refer to the official documentation.

You can also check out the with method, which does the same thing.

Comments 2 total

Add comment