Programmatically updated a files field

Trying to fetch all the images attached to a page and appending them to a files field.

$front   = [$product->images()->search('vfro')];
$side    = [$product->images()->search('vtqp')];
$back    = [$product->images()->search('vtqd')];
$gallery = $product->images();

$product->update([

    // Update front, side and rear view
    'front' => $front,
    'side'  => $side,
    'back'  => $back,

    // Update the gallery
    'gallery' => $gallery
]);

Front side and rear views are single images and it’s working just fine. Gallery is all the images. It doesn’t work. I tried a bunch of possible solutions. Passing it as an explicit array, Data::encoding it, Yaml:: encoding it, merging the array.

Nothing seems to work. Since I exhausted all the profanities at my disposal, what’s the correct approach to update a files field with multiple files?

A files field expects an array of file ids/uuids. That’s why your code works for single images, but not for multiple. Convert a collection of images to an array:

$gallery = $product->images()->pluck('uuid', ','); // passing the comma to get a flat array
1 Like