How to append an image to a product

I import products essentially by calling productrepository.upsert(['name'=>...]);
What is the established best practice to append product pictures, so that they get saved to disk and all the media_* tables get populated?


Well, I don’t know the established best practice, but I know what works :wink: There are two steps to do here. First, you have to put the images to the media library and second, you have to assign them to the product.

This is the first step - add the image to the media library:

$mediaFile = new MediaFile($filePath, $mimeType, $fileExtension, $fileSize);
$mediaId = $this->mediaService->createMediaInFolder('product', $context, false);

And this is the second step - add a record with product ID and media ID to the product_media repository:

foreach ($mediaIds as $mediaId) {

        //generate unique ID for the product-media row
        $productMediaId = Uuid::randomHex();

        //add to the product_media repository
        $data = ['id' => $productMediaId, 'productId' => $productId, 'mediaId' => $mediaId];
        $this->productMediaRepository->create([$data], $context);


An article on my Shopware 6 blog explains it in more depth: [How to add images to products programmatically in Shopware 6 -]

That is awesome, thank you so much.

My rather ugly approach was to first create the entity via the product repository with

        'id' => <productid>,
        'productNumber' =>...,
        'media' => [
                'id' => ...,
                'position' => 0,
                'media' => [
                        'id' => ...,
                        'fileName' => ...,
                        'fileSize' => ...,
                        'mediaFolderId' => $this->getDefaultProductMediaFolderId(),

then load that entity, work out the directory the picture is expected to be in, and save the image there.
It kinda worked, but screwed the thumbnail generation.