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.

Home Page:https://splade.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

bardolf69 opened this issue · comments

  • Laravel Version: 10.43.0
  • PHP Version: 8.2.15
  • Splade JS Version (npm): 1.4.16
  • Splade PHP Version (composer): 1.4.16
  • Dev environment (OS, Sail/Valet/etc): Ubuntu 22.04, Nginx

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();
}

Duplicate of #540, let's continue there.