Saturday, February 26, 2022

[FIXED] Use JSON_UNESCAPED_UNICODE in API resource laravel

Issue

when i want to return texts in api resource get the following response :

{"data":{"message":"\u۰۶۳۳\u۰۶۴۴\u۰۶۲۷\u۰۶۴۵ \u۰۶۲۸\u۰۶۳۱ \u۰۶۲a\u۰۶۴۸"},"status":۰}

this problem solved in response()->json when i add following code to response :

return 200, [], JSON_UNESCAPED_UNICODE

like:

return response()->json(['message' => 'my utf8 text'], 200, [], JSON_UNESCAPED_UNICODE);

but in api resource i can't add this code to response

api resource code:

    public function toArray($request) {
        return [
            'id' => $this->id,
            'userId' => $this->user_id,
            'title' => $this->title,
            'text' => $this->text,
            'isAccepted' => $this->is_accepted,
            'viewCount' => $this->view_count,
            'likeCount' => $this->like_count,
            'dislikeCount' => $this->dislike_count,
            'commentCount' => $this->comment_count,
            'createdAt' => date('Y-m-d H:i:s' , strtotime($this->created_at)),
        ];
    }

    public function with($request) {
        return [
          'status' => Status::SUCCESS
        ];
    }

how i can solve this problem ?


Solution

Try to edit below function in "Illuminate\Http\JsonResponse.php"

public function __construct($data = null, $status = 200, $headers = [], $options = 0)
{
    $headers = ['Content-Type' => 'application/json; charset=UTF-8',
        'charset' => 'utf-8'];
    $options = JSON_UNESCAPED_UNICODE;
    $this->encodingOptions = $options;

    parent::__construct($data, $status, $headers);
}


Answered By - Vinz

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.