ADD TOP-LEVEL DATA WITH RESOURCE

Jun 02, 2025 Copy Link

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.

Share via

Mahmoud Ramadan

Mahmoud Ramadan

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

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autoloading in Versions Before v12.8

    PREMIUM

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to welcome Laravel v12

    PREMIUM

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using TCPDF

    FREE