PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 26, 2022

[FIXED] Use JSON_UNESCAPED_UNICODE in API resource laravel

 February 26, 2022     laravel, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing