3
votes

I try to return as json added attribute which I get with the following method in my User model but I keep getting

 "message": "Malformed UTF-8 characters, possibly incorrectly encoded",
    "exception": "InvalidArgumentException",
    "file": "/var/www/timetool/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php",

the code

   /**
     * @return string
     */
    public function getAvatarImageAttribute($value)
    {

        if($this->hasMedia('avatar')) {
             $image = $this->getMedia('avatar');
             $img = \Intervention\Image\ImageManagerStatic::make($image[0]->getPath())->encode('data-url');
         }
         elseif (isset($this->blob->dokument)) {
             $img = 'data:image/jpeg;base64,'. base64_encode($this->blob->document);
         } else {
             $img = '';
         }

         return $img;
    }

in controller I have

return \Response::json($users, 200, array('Content-Type' => 'application/json;charset=utf8'), JSON_UNESCAPED_UNICODE);
3

3 Answers

2
votes

I'm thinking it's related to JSON needing only UTF8 chars and your blob may have invalid chars. Try utf8_encode($img). http://at2.php.net/manual/en/function.utf8-encode.php In your controller just return. Laravel will build a proper json response for you.

1
votes

Paste this function top of your document:

public static function convert_from_latin1_to_utf8_recursively($dat)
{
   if (is_string($dat)) {
      return utf8_encode($dat);
   } elseif (is_array($dat)) {
      $ret = [];
      foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);

      return $ret;
   } elseif (is_object($dat)) {
      foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);

      return $dat;
   } else {
      return $dat;
   }
}

Call the above function to convert the content. It has a parameter just it need the value of blob image (binary):

$img = $this->convert_from_latin1_to_utf8_recursively($this->blob->document)
0
votes

In my case the problem was the encoding of the controller. The solution was to convert it to UTF8 and the bug was fixed.