tuncdogu55's avatar

Laravel Media Library — How to attach the same uploaded file to multiple models?

Hello,

I’ve been working with the Spatie Laravel Media Library package and ran into a common problem when trying to attach the same uploaded file to multiple models (for example, both a Course and a Product model).

When I do something like this:

foreach ($images as $image) {
    $course->addMedia($image)->toMediaCollection('images');
    $product->addMedia($image)->toMediaCollection('images');
}

I quickly get the following error:

File ... does not exist in FileDoesNotExist.php

As far as I understand, when you call addMedia($image) with an UploadedFile, Spatie moves the file from PHP’s temporary upload directory to the media library path — meaning the file is no longer available for the second model.

What is your suggestions about that ?

0 likes
1 reply
tuncdogu55's avatar
tuncdogu55
OP
Best Answer
Level 1
foreach($images as $image){
                $course->addMedia($image)
                    ->preservingOriginal() // blocking the deleting original file. 
                     ->toMediaCollection('images');

                $product->addMedia($image)
                     ->toMediaCollection('images');
                     
}

preservingOriginal Middle Method worked. Thanks.

Please or to participate in this conversation.