Laravel – Json Encode Works Fine But Returns Malformed UTF-8 Error Regardless


The JSON is returned correctly encoded but json_last_error equates to 5 thus Laravel throws this exception on response creation in JsonResponse->setData().

Related References

A resolved bug report for symfony and PHP 7.3: mentions this exact issue. That is:

If a json_encode()/json_decode() without JSON_THROW_ON_ERROR encoding option set throws an error, any subsequent call to the same with that flag set will not reset the error of the previous call.

The JSON_THROW_ON_ERROR RFC mentions this behavior as by design:

Unfortunately Laravel’s code uses the flag but does not cater for this behavior and throws exception if json_last_error() returns a non zero value. Which in this case should have been ignored as it will always reference the previous error. Perhaps a version check should be added.


I have also searched the bowls of my application and haven’t found the misbehaving json_encode/json_decode without JSON_THROW_ON_ERROR set so I am sure it is internal to Laravel before Middleware calls.

Additional Context

This suddenly started happening today in our server. It happens when users connect to the server through the web app from select systems. Even though system kind should not affect server side response generation but still web app always generates this error for specific PCs/Mobiles.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *