Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to leverage the MetaResponse as per the documentation #646

Open
mophpdev opened this issue Sep 18, 2024 · 0 comments
Open

How to leverage the MetaResponse as per the documentation #646

mophpdev opened this issue Sep 18, 2024 · 0 comments

Comments

@mophpdev
Copy link

mophpdev commented Sep 18, 2024

I want to add global top-level meta data.

https://laraveljsonapi.io/docs/3.0/responses/#meta-response
This document doesn't tell you enough in terms of how you can add top-level meta data.

I achieved this by using the index() method.

MyController extends BaseController extends JsonApiController

// BaseController.php

use LaravelJsonApi\Contracts\Routing\Route;
use LaravelJsonApi\Contracts\Store\Store;

public function index(Route $route, Store $store)
{
    $response = parent::index($route, $store);

    if ($response instanceof DataResponse) {
        // Add any top-level metadata
        $response = $response->withMeta([
            'foo' => 'bar',
            'server_time' => now()->toIso8601String(),
        ]);

        // Add any global custom headers
        $response = $response->withHeader('X-API-Version', '1.0');
    }

    return $response;
}

In the documentation its stated as:

Meta Response
Our LaravelJsonApi\Core\Responses\MetaResponse class allows you to return a a JSON:API response that has a top-level meta member, but no data member. This is allowed by the specification.

To use this class, you just need to provide the meta value to either the constructor or the static make method. The meta value can be an array or a Laravel collection.

For example:

use LaravelJsonApi\Core\Responses\MetaResponse;

return new MetaResponse(['foo' => 'bar']);
// or
return MetaResponse::make(['foo' => 'bar'])
    ->withHeader('X-Foo', 'Bar');

What is the best approach to achieving or leveraging this MetaResponse()?

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant