1

My application supporting multiple language.

My Controller,

 public function index(Request $request) {
    return DB::table('offer_types')
                    ->join('offer_type_details', 'offer_type_details.offer_types_id', '=', 'offer_types.id')
                    ->where('offer_type_details.languages_id', $request->language_id ? $request->language_id : 1)
                    ->get();
}

In case of Arabic, it returns following json,

    [{
    "id": 1,
    "description": "desc",
    "offer_types_id": 1,
    "languages_id": 2,
    "title": "\u062d\u0632\u0645"
}, {
    "id": 2,
    "description": "desc",
    "offer_types_id": 2,
    "languages_id": 2,
    "title": "\u0641\u0646\u0627\u062f\u0642"
}]

How can I encode this arabic value in Laravel 5.2?

gsk
  • 2,329
  • 8
  • 32
  • 56

2 Answers2

3

Try to do this:

$data = DB::table('offer_types')
                    ->join('offer_type_details', 'offer_type_details.offer_types_id', '=', 'offer_types.id')
                    ->where('offer_type_details.languages_id', $request->language_id ? $request->language_id : 1)
                    ->get();

return Response::json($data, 200, [], JSON_UNESCAPED_UNICODE);

Or

return response()->json($data, 200, [], JSON_UNESCAPED_UNICODE);
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • second one worked fine.. thanks... is there any method to set globally? – gsk Mar 15 '16 at 16:00
  • What do you mean? If you're asking about `Response::`, you could try to use `\Response::`. – Alexey Mezenin Mar 15 '16 at 16:03
  • no.. I dont want to repeat in every controller, I am developing APIs. So is there any method to set encoding globally in application? – gsk Mar 15 '16 at 16:20
  • I think it's the easiest and more readable way to do this, but if you really want to do this globally, you could try this solution: https://laracasts.com/discuss/channels/laravel/how-to-prevent-laravel-from-returning-escaped-json-data – Alexey Mezenin Mar 15 '16 at 16:27
2

Do JSON encode with JSON_UNESCAPED_UNICODE flag.

json_encode($multibyte_string, JSON_UNESCAPED_UNICODE);

It encodes multibyte Unicode characters literally. So the Unicode characters will not be escaped like \uXXXX.

Harikrishnan
  • 9,688
  • 11
  • 84
  • 127