1

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.

Andrew Willis
  • 2,289
  • 3
  • 26
  • 53
  • How are you implementing the middleware in routes.php? – Ralla Jul 15 '16 at 13:31
  • I was adding it in the `App\Http\Kernel` middleware default middleware stack. It hits the middleware but what is returned is not a Dingo API response, it's a Illuminate response so it doesn't have the ability to add the metadata without hacking apart and rebuilding the response text which seems very superfluous considering that it's just been turned into JSON from an array... – Andrew Willis Jul 15 '16 at 13:37
  • I have done something similar, try adding the middleware to the `protected $routeMiddleware [];` in `App\Http\Kernel` and then create a Route group with that middleware: `$api->group(['middleware' => ['your-middle-ware']], function ($api) { ... }` – Ralla Jul 15 '16 at 13:43

0 Answers0