Laravel 5.5:将网址添加到json对象以保存多张图片

时间:2019-05-27 08:17:50

标签: php json laravel

我需要使用Laravel保存多张图片。图片分别存储在磁盘上,指向这些位置的链接存储在数据库中的JSON文件中。因此,每个用户在数据库中都有一个列,其中包含:

{"images": ["/user/57/house-11-1.png", "/use/57/house-12-2.png"]}

因此,当用户上传文件并单击“保存”时,将发生以下代码:

    $path = $this->processImage($request, $user->id, $house->id);
    /* uploads the image to the server and pass path of the image*/
    if ($path) {
        $jsonstring = $house->images;
        dd($jsonstring);
        $arr = json_decode($jsonstring);
        $arr['images'] = [$path];
        $json = json_encode($arr);
        dd($json);
        $house->images = $json;
        $house->save();
    }

使用的laravel模型称为userHouse,并将图像另存为:

class userHouse extends Model implements Changeable
{
    protected $casts = [
        'images' => 'array',
    ];
...
}

processImage函数:

private function processImage($request, $userID, $houseId)
{
    $path = null;
    $number = rand(1, 99);
    if ($request->hasFile('image')) {
        $image = Image::make($request->file('image'))
            ->resize(750, null, function ($constraint) {
                $constraint->aspectRatio();
            })
            ->encode('png');
        $path = "/vendors/{$userID}/horse-{$houseId}-{$number}.png";
        Storage::disk('fileadmin')->put($path, $image->encoded);
    }

    return $path;
}

我得到的错误是:

[2019-05-27 08:01:15] local.ERROR: Serialization of 'Illuminate\Http\UploadedFile' is not allowed {"userId":57,"email":"info@test.com","exception":"[object] (Exception(code: 0): Serialization of 'Illuminate\\Http\\UploadedFile' is not allowed at /Users/dsfsdf/ah-website/user/laravel/framework/src/Illuminate/Session/Store.php:128)
[stacktrace]

如何将URL添加到数据库中的JSON字符串?上传单个图像即可。

1 个答案:

答案 0 :(得分:0)

我能想到的是processImage方法无法处理请求中的多个上载文件。

此外,IMO,此方法实际上应接收UploadedFile对象,而不是整个请求。

因此,代码类似于:

$images = $house->images;

foreach ($request->images as $uploadedFile) {
    $images[] = $this->processImage($uploadedFile, $user->id, $house->id);
}

$house->images = $images;
$house->save();

此外,如果您在模型中将images属性定义为数组,则无需进行解码/编码,因为laravel已经这样做了。