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

kaju74's avatar

How to prevent Laravel from returning escaped JSON data?

Hi.

I'm implementing an API Server w/ Laravel which should return JSON...so it's fine, that the framework automatically support this. My problem is, that Laravel returns escaped data as soon as unicode characters (like german umlauts) will be used.

My host application sends stuff like this:

{"id": "53SEDXAF", "name": "Testhülse"

My API Controller simply return that stuff:

// return status
return [
    'status' => 'success',
    'data'   => Request::all(),
];

If I take a look at the response (e.g. using Fiddler), the data value will be returned using escape characters:

{"status":"success","data":{"data":{"id":"SEDXAF","name":"Testh\u00fclse"}}}

My request header looks like:

Accept: */*
Host: xyz
User-Agent: xyz
Content-Type: application/json; charset: utf-8
Accept-Charset: utf-8
Connection: Keep-Alive
Content-Length: 38
Pragma: no-cache

So, why does Laravel returned it w/ escaped characters? I thought, if I pass utf-8 as the character set in the header, the returned data will be unescaped...

I know, that I can return the JSON like this:

return response()->json(data, 200, [], JSON_UNESCAPED_UNICODE);

...but is there no other way to:

a) set this globally? b) let Laravel return JSON dependant of what character-set has been passed in the header?

Thank you, Marc

0 likes
5 replies
jasonlewis's avatar
Level 1

I'm not so sure Laravel has any built-in content negotiation that automatically handles something like this. AFAIK it's up to you to implement the algorithms that determine the response and character set used, etc.

That said, I don't think there's a way to globally define the JSON options used in json_encode. I suppose you could set up some kind of method in a base controller that lets you handle the content negotiation and setting the correct JSON options.

public function respondWithJson($data)
{
    $options = app('request')->header('accept-charset') == 'utf-8' ? JSON_UNESCAPED_UNICODE : null;

    return response()->json($data, 200, $options);
}
phildawson's avatar

Is there any reason for getting it unescaped?

Why not convert it back on the other end?

xhr.responseText; // Testh\u00fclse

JSON.parse(xhr.responseText); // Testhülse
=
xhr.responseJSON; // Testhülse
kaju74's avatar

Hi.

Thank you for the quick answers. No, it's not just a problem by getting the data escaped cause I could unescape it, I only excepted, that Laravel will return it unecaped if I pass utf-8 in the request header. I thought, there's any convention on how to handle unicode json data and when to escape it like in my example above (I know, I've forgot the '}' character in my json data ;-)

Regards, Marc

TimothePearce's avatar

If you are working with collection, you can do:

$myCollection->toJson(JSON_UNESCAPED_UNICODE)

Please or to participate in this conversation.