I'm working with a Laravel application where I need to manage multiple image uploads for an existing project. I'm trying to update the image list by first deleting old images from storage, then adding the paths of these old images to a new array along with the paths of newly uploaded images. However, when I upload new images and attempt to update the array that holds the image paths, I encounter an issue where the existing image paths return as an empty string in the format [{}, "new_image_path"].
Additionally, I've tried using json_decode on the array, but I get an error saying json_decode(): Argument #1 ($json) must be of type string, array given.
$pricelists = [];
$pricelistcount = 1;
if ($request->hasFile('project_pricelist_url')) {
$existingPricelists = $project->project_pricelist_url ?: [];
foreach ($existingPricelists as $existingPricelist) {
Storage::delete('public/project/pricelists/' . $existingPricelist);
}
foreach ($existingPricelists as $existingFilename) {
$pricelists[] = $existingFilename; // Add existing filenames to the new array
}
foreach ($request->file('project_pricelist_url') as $file) {
$currentDateTime = now()->format('YmdHis');
$filename = $initials . "_" . $pricelistcount . '_' . $currentDateTime . '.' . $file->getClientOriginalExtension(); // Buat nama unik untuk setiap file
$file->storeAs('public/project/pricelists', $filename); // Simpan file ke direktori yang diinginkan
$pricelistcount++;
$pricelists[] = $filename; // Simpan nama file dalam array
}
$project->project_pricelist_url = json_encode($pricelists);
}
How can I correctly manage and update the list of image paths during the upload process to ensure both old and new image paths are retained and formatted correctly?