Hi,
I’m building a frontend form that lets users upload images. The image gets send as a base64 encoded string to the route. I create and try to update the images like so:
if (isset($formData['images']) && is_array($formData['images'])) {
$files = [];
foreach ($formData['images'] as $index => $imageData) {
// Extract the base64 data and file type
if (preg_match('/^data:image\/(\w+);base64,/', $imageData['url'], $type)) {
$base64Data = substr($imageData['url'], strpos($imageData['url'], ',') + 1);
$imageContent = base64_decode($base64Data);
$extension = strtolower($type[1]); // e.g., 'png', 'jpg', 'gif'
$filename = Str::slug($formData['title']) . '-' . ($index + 1) . '.' . $extension;
$contentpath = $newEventPage->root();
F::write($contentpath . '/' . $filename, $imageContent);
try {
$file = $newEventPage->file($filename)->update([
'caption' => $imageData['caption'] ?? '',
'copyright' => $imageData['copyright'] ?? '',
]);
$files[] = $file;
} catch (Exception $e) {
throw new Exception('Failed to create image file for image ' . ($index + 1) . ': ' . $e->getMessage());
}
} else {
throw new Exception('Invalid image data provided for image ' . ($index + 1));
}
}
if (!empty($files)) {
$newEventPage->update([
'gallery' => $files,
]);
}
}
Both images get written and are then found in the page folder. However only the first image is updated and gets a .txt file. Does anybody know why?
Thanks for the help!