Add Top-Level Data with Resource

Jun 02, 2025

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.

AI Assistant

Summarize, simplify, and ask questions about this content using your preferred AI provider.

Text Tools

Generate cleaner and easier-to-read versions of this content instantly

Have a Question?

Ask anything related to this content and get a focused AI-generated answer.

0/500
Mahmoud Ramadan
Author

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.