For context first, the company I work at is changing storage locations. We have some forms with different questions, and the images related to those are either on base64 inside the text on the questions table with the rest of the text, or on AWS cloud.
As the text of each questions uses HTML being written in CKEditor with images in-between, we used to save to database exactly what the HTML CKEditor outputs, using for example inside the text, the img tag where the src would be the URL to the our AWS storage like "aws/image.png"".
As we upgraded recently to a robust local NAS, we now want to abandon AWS and use images hosted locally. The problem is that I'm trying to download each one by getting the URL from inside the HTML saved on the database text column, using a regex for getting the src of every img tag, then using file_get_contents to save locally using a new pattern of directories (different from the current AWS).
public function download_img($url, $question_id): string
{
$public_question_dir = 'images/questions/'.$question_id.'/';
if (!file_exists(public_path() . '/public/' . $public_question_dir)) {
mkdir(public_path() . '/public/' . $public_question_dir, 0777, true);
}
$filename = Str::random(40) . '.png';
$fileContents = file_get_contents($url);
Storage::disk('public')->put('/' . $public_question_dir . $filename, $fileContents);
return $public_question_dir . $filename;
}
The download works great. It saves to the right public symbolic link folder inside storage/app/public/ as it should, but now I need to do a str_replace on the text column inside the database to replace the old URL to new one locally hosted.
The problem is, I have no idea how to do that replacement, because if the URL is resolved using url(), the link will only work for a given server.
If I just replace the the URL using something like
$question = Question::find(129);
# image[0] = old aws link
# image[1] = return of download_img, local path
$question->question_text = str_replace($image[0], url($image[1]), $question->question_text);
$question->save();
the URL is resolved for the current environment, so it will save https://127.0.0.1/, but I need for it the work on every env, production, testing and local. I tried saving to the database something like {{ url(public_link) }} , but then the blade does not resolve it, it prints as a {{}} string as it is already rendering the HTML by using {! !}.
I have no idea how should I do this in a way that works for every environment, or that blade template can interpret and render correctly. Will I have to treat every single URL in the whole HTML text everytime the HTML is being loaded? Is there a way to do this without using plain base64 inside the text of the database?
Thanks in advance for any help and input.