aschidlovsky's avatar

Issue str_replace always overwrites with a blank value

I am trying to upload multiple images in base64 from rich text editor. My idea was to upload all the images and replace base64 img src in thread content with newly created image path. I am using spatie media library and Quill Editor.

Here is the function. I am using str_replace to try and replace the base64 string.

public function update(Request $request, $channel, Thread $thread)
{
    $this->authorize('update', $thread);

    $body = $request->body;
    $images = $request->images;


    $thread->update($request->all());

    if ($images) {
        foreach ($images as $image)
        {
            // Create a new image from base64 string and attach it to thread in thread-images collection
            $thread->addMediaFromBase64($image)->toMediaCollection('thread-images');

            // Get all images as we will need the last one uploaded
            $mediaItems = $thread->load('media')->getMedia('thread-images');

            // Replace the base64 string in thread body with the url of the last uploaded image
            $thread->body = str_replace($image, '<img src="' . $mediaItems[count($mediaItems) - 1]->getFullUrl() . '">', $thread->body);
        }
    }

     $thread->update();

    return $thread;
}

The issue is that it always overwrites the base64 string with a blank value. I have printed the $mediaItems[count($mediaItems) - 1]->getFullUrl() to prove I can retrieve the value. Please help.

0 likes
2 replies
Snapey's avatar

use $thread->save() at the end, not update

aschidlovsky's avatar

@snapey Thanks for your reply. I appreciate you trying to help.

I did try $thread->save(). Still the same result. Do you see any other way I might try to accomplish what I am trying to do?

Or any other issues with my current solution?

Please or to participate in this conversation.