protonemedia / laravel-splade

💫 The magic of Inertia.js with the simplicity of Blade 💫 - Splade provides a super easy way to build Single Page Applications (SPA) using standard Laravel Blade templates, and sparkle it to make it interactive. All without ever leaving Blade.
https://splade.dev
MIT License
1.47k stars 111 forks source link

uploading multiple files to an empty spatie media collection only stores the last file in the array. #556

Closed bardolf69 closed 7 months ago

bardolf69 commented 7 months ago

Description:

When I upload multiple files to an empty spatie media collection, only the last file in the array is stored. But if I then go back into the SAME form and add another 2 files, all 3 will be saved. When I do the initial post I can see the multiple files being sent to the backend and after that first file is in the collection everything behaves exactly the way it should. But if I remove all files from the collection and try to add multiple files again it will once again only sync the last file in the array.

Steps To Reproduce Issue:

Create a model with a spatie media collection.

public function registerMediaCollections(): void
{
    $this->addMediaCollection('files');
}

Create a form with a file upload.

public function addFiles(Topic $topic)
{
    $files = ExistingFile::fromMediaLibrary($topic->getMedia('files'));
    return view('admin.teachers.addFiles', ['topic' => $topic, 'files' => $files]);
}

admin.teachers.addFiles is a modal as per below

<x-splade-modal>
    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 bg-white p-4 h-3/5">
            <x-splade-form :action="route('teacher.topic.storeFiles', $topic)" :default="['files'=>$files]">
                <x-splade-file label="Change files" filepond multiple preview server name="files[]"  />
                <x-splade-submit label="Sync Files" class="mt-4" />
            </x-splade-form>
        </div>
    </div>
</x-splade-modal>

Use HandleSpladeFileUploads::syncMediaLibrary to save the uploaded files

public function storeFiles(Request $request, Topic $topic)
{
    HandleSpladeFileUploads::forRequest($request);  
    $validated = $request->validate([
        'files' => 'nullable|array',
        'files.*' => 'required|file',
    ]);

    HandleSpladeFileUploads::syncMediaLibrary(
        request: $request,
        subject: $topic,
        key: 'files',
        collectionName: 'files'
    );

    return redirect()->back();
}
pascalbaljet commented 7 months ago

Duplicate of #540, let's continue there.