Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jordan.dobrev.88@gmail.com's avatar

Add additional data to Rest response

Hi everyone,

While L5 was still in development I used the middlewares to add additional data after each rest response like this:

$response = $next($request);

if (!isset($response['date'])) {
    $response['date'] = date('c');
}

return $response;

After the official release Taylor changed some stuff and the response content is build before it hits the middleware. I can make it work with decoding the response content, adding the additional parameter and encoding it again, but it's the same job done twice. Is there a neater way do it?

0 likes
10 replies
bjorntheart's avatar

@LPMadness can't you hook into the $request and do a before filter like this

if (!isset($request['date'])) {
    $request['date'] = date('c');
}

return $next($request);
bjorntheart's avatar

@pmall thanks for your useful reply. Do you have any better suggestions or an actual solution to the problem

bjorntheart's avatar

Ok @LPMadness, I think this might help you.

I create a Middleware called AddToRequest and registered it in Kernel.php. See the code below AddToRequest.php

<?php namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;

class AddToRequest {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->request->add(['dummy' => 'hey man', 'date' => Carbon::now()]);

        return $next($request);
    }
}

Kernel.php

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\VerifyCsrfToken',
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'inject' => 'App\Http\Middleware\AddToRequest'
    ];

}

In the handle() method of the AddToRequest Middleware, I set two variables and add it to the request

$request->request->add(['dummy' => 'hey man', 'date' => Carbon::now()]);

Then, in my controller I use the inject middleware

public function __construct()
{
    $this->middleware('inject');
    $this->middleware('guest');
}   

In the index() method of the controller I inject the use Illuminate\Http\Request object and pull the variables I set in the middleware from the request object as follows:

public function index(Request $request)
{
    dd($request->get('dummy'), $request->get('date'));

    return view('welcome');
}

I hope that helps :-)

jordan.dobrev.88@gmail.com's avatar

@bjorntheart Sometimes the rest functionality is doing complex calculations so I need to add it after the request is processed. I use the datetime as a last activity record from the server for lots of other stuff like: execution time, cache, is alive checks, logging, etc. I am also adding other parameters to the response that my API needs, but in order to keep things simple I just showed the datetime filter as an example to what I am trying to achieve.

bjorntheart's avatar

@LPMadness hey, just noticed your reply after mine. Does what I posted help at all, or am I missing something?

Please or to participate in this conversation.