Laravel“格式错误的 UTF-8 字符,可能编码错误”,如何修复?

fef*_*efe 6 attributes json blob response laravel-5.5

我尝试返回为 json 添加属性,我在用户模型中使用以下方法获得该属性,但我不断收到

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

代码

   /**
     * @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;
    }
Run Code Online (Sandbox Code Playgroud)

在控制器中我有

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

Gor*_*ski 5

我认为这与仅需要 UTF8 字符的 JSON 有关,并且您的 blob 可能包含无效字符。尝试 utf8_encode($img)。https://www.php.net/manual/en/function.utf8-encode.php 在您的控制器中只需返回即可。Laravel 将为您构建正确的 json 响应。