I am trying to add user-specific Metadata to every API response using Dingo Api. I assumede this would be done in an AddMetadata
middleware:
<?php
namespace App\Http\Middleware\Api;
use Closure;
use Dingo\Api\Http\Request;
class AddMetadata {
public function handle(Request $request, Closure $next)
{
$response = $next($request);
/*
* Dingo API response has the ability to modify metadata responses
*/
if ($response instanceof \Dingo\Api\Http\Response) {
$oldMeta = $response->getMeta();
$meta = array_merge($oldMeta, $request->user()->metadata());
$response->setMeta($meta);
}
return $response;
}
}
What I find is the Response at this point is no longer a Dingo API response, therefore I am unable to add metadata. I tried using the Dingo\Api\Http\Response::makeFromExisting()
method to create a new response from the old request, I've also tried instantiating a new response but it appears that the Dingo Api response is processed before getting to the middleware.
What would be the most efficient way of adding the user-specific metadata to the response? Ideally I don't want to be adding it to every API endpoint individually.