I have an API on Laravel 7.0, where all responses are automatically transformed to json by default because of api routes middleware.
The problem is that some of the responses cause the "Malformed UTF-8 Characters" error on JSON Response, so I have to manually process all data before I return it on controller, like this:
return FormatString::convertLatin1Utf8($data);
It works fine, but now I have to return data this way in every single api method.
I have a middleware to process cryptography on requests in and out, like this:
public function handle($request, Closure $next) {
//... some processing before request
$request = $next($request)->original;
//... some processing after request
return response()->json($request);
}
I thought of formatting my data on middleware after the request is processed, so I wouldn't have to call FormatString in every method, like this:
public function handle($request, Closure $next) {
//... some processing before request
$request = $next($request)->original;
//... some processing after request
$request['data'] = FormatString::convertLatin1Utf8($resquest['data']);
return response()->json($request);
}
But when $next($request)
is called it tries to process the Json response on the unformatted data and throw the error I'm trying to avoid.
Is there any way to get the request data before Laravel tries to process into Json, without having to always format it on controller return?
$request
there – lagbox Sep 24 '20 at 20:28ApiController
with a method likegetResponse($data)
, do you conversion in there, and have all your controllers extend that controller callingreturn $this->getResponse($data);
– Wesley Smith Sep 24 '20 at 20:36