i have database column images
in Laravel, which contains list of images like below ["f3bd5ad57c8389a8a1a541a76be463bf.png","37aa5dfc44dddd0d19d4311e2c7a0240.jpg","e287f0b2e730059c55d97fa92649f4f2.jpg"]
now user wants to delete f3bd5ad57c8389a8a1a541a76be463bf.png i can delete image from path but i want to delete this image from the array list too. for deleting from path i can used
$path=$request->picloc;
$image_path = public_path($path);
if (file_exists($image_path)) {
File::delete($image_path);
// delete from database too
return response('file deleted');
}
how can i achieve that in Laravel? thanks
CodePudding user response:
If you convert your images array
to a collection
, you can use the either the filter
or reject
methods to remove the desired element.
Using reject
:
$images = [
"f3bd5ad57c8389a8a1a541a76be463bf.png",
"37aa5dfc44dddd0d19d4311e2c7a0240.jpg",
"e287f0b2e730059c55d97fa92649f4f2.jpg"
];
$imagesToRemove = ['f3bd5ad57c8389a8a1a541a76be463bf.png'];
$collection = collect($images)->reject(function ($value) use ($imagesToRemove) {
return in_array($value, $imagesToRemove);
});
dd($collection);
Using filter
:
$images = [
"f3bd5ad57c8389a8a1a541a76be463bf.png",
"37aa5dfc44dddd0d19d4311e2c7a0240.jpg",
"e287f0b2e730059c55d97fa92649f4f2.jpg"
];
$imagesToRemove = ['f3bd5ad57c8389a8a1a541a76be463bf.png'];
$collection = collect($images)->filter(function ($value) use ($imagesToRemove) {
return !in_array($value, $imagesToRemove);
});
dd($collection);
Both achieve the same outcome.