How to control order of images in spatie media library field while saving?

400 views Asked by At

Laravel project with Filament admin panel. I have a SpatieMediaLibraryFileUpload field for images in my Filament resource. It's multiple. When I choose or drag&drop files there they have some order in preview. But after I save them their order is changed. But it's a bit confusing thing - before you save them, you can't be sure what order you'll get. What we could do to be sure that order in the preview will be saved? Thanks!

My field looks like that now:

'images' => SpatieMediaLibraryFileUpload::make('images')
                ->label(__('general.images.label'))
                ->collection('images')
                ->columnSpan(2)
                ->imagePreviewHeight('250')
                ->panelLayout('grid')
                ->image()
                ->multiple()
                ->enableOpen()
                ->enableReordering()
                ->uploadProgressIndicatorPosition('left')
                ->disk(app()->environment('local') ? 'public' : config('media-library.disk_name'))
                ->visibility(function () {
                    return (config('media-library.disk_name') === 's3') && config('someproject.store_images_private', true) ? 'private' : 'public';
                })
                ->reactive(), 

I tried to find info how I could save order of images in preview, but no luck yet. It looks a bit tricky.

1

There are 1 answers

0
Jeyhun Rashidov On

Ensure that the order_column attribute of the media items is set correctly. The Spatie Media Library uses this column to determine the order of media items.

For example, when you're attaching media to a model, you might do something like:

$images = $request->input('images');
foreach ($images as $index => $image) {
    $model->addMedia($image)
        ->toMediaCollection('images')
        ->setCustomProperty('order_column', $index);
}