I\'m trying to build a REST api using Laravel Framework, I want a way to force the API to always responed with JSON not by doing this manulaly like:
return Respo
You can create an After Middleware and change structure of all responses
Middleware:
namespace App\Http\Middleware;
use Closure;
class ChangeResponseStructureMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
$newContent = [
'data' => $response->getOriginalContent(),
'context' => [
'code' => $response->getStatusCode()
]
];
return $response->setContent($newContent);
}
}
this middleware will force the response content to be like
{
"data": "response content of controller",
"context": {
"code": 200 // status code
}
}