Laravel "Malformed UTF-8 characters, possibly incorrectly encoded", how to fix?
Asked Answered
G

3

6

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);
Glacier answered 1/11, 2017 at 14:58 Comment(0)
C
5

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

Chassepot answered 8/1, 2018 at 20:13 Comment(0)
P
1

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)
Pyromancy answered 17/4, 2021 at 5:27 Comment(0)
L
0

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

Lucubration answered 17/12, 2020 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.