laravel modify all json responses code example

Example 1: laravel modify all json responses

this middleware would perform its task after the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform action

        return $response;
    }
}

Example 2: laravel modify all json responses

public function handle($request, Closure $next)
{
    // get response
    $response = $next($request);
    
    // if response is JSON
    if($response instanceof JsonResponse){

        $current_data = $response->getData();

        $current_data->userData = ['attach some additional user data'];

        $response->setData($current_data);

    }

    return $response;
}