Igor Simic
11 months ago

Laravel - modify json response


How to Customize JSON from Rest API response? Let's say we want to attach some additional user data to every Laravel JSON response.

We can do this by using Laravel middleware.
php artisan make:middleware UserData 
Open Kernel and add this line to route middleware:
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    ...
    'userData' => \App\Http\Middleware\UserData::class,
];
Now we will include this middleware as route filter:
Route::group(['middleware' => ['userData']], function(){
...
// your routes
}];

And now let's edit middleware itself:
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;
}