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

SinghWithLaravel's avatar

How to Add a specific key in each API response.

I want to add a specific key in each API reponse in Laravel. How can i do that ?

0 likes
3 replies
tykus's avatar

Do you mean to add the key in the JSON payload? Is it the same key for every response in a given user's "session"; is it unique for each user?

Are you using Laravel's API Resources?

tykus's avatar

If you want it in every JSON response, then I would consider a middleware which appends to the response content:

// AddTokenToResponse Middleware
public function handle($request, Closure $next)
{
	return tap($next($request), function (JsonResponse $response) {
		$modifiedData = array_merge($response->getData(true), [
			'token' => uniqid('tok_')
		]);
		$response->setData($modifiedData);
	});
}

This should give you an idea; it takes the response data, appends the token, and then sets the new data on the response. Your token will likely be coming from elsewhere, but this same general approach will apply. Make sure to add the new middleware either as a route middleware, or for the entire api middleware group as appropriate to your application.

Please or to participate in this conversation.