Skip to content
Advertisement

Laravel – delete whole collection

I have images for articles, and when I am updating article I would like to check if the images are the same, if not I would like to delete them but if it is possible I would like to delete the whole collection without another query, something like what I have in the code below $images->delete();. This is my function:

$images = Media::where('article_id', $article->id)->get();

    foreach($images as $image) {
        $article_images[] = $image->original_name;
    }

    foreach($files as $file) {
      $filePathArr = explode('/', $file);
      $fileName = array_pop($filePathArr);
      $originalFile = explode('-', $fileName);
      $originalFileName = array_pop($originalFile);
      $newFiles[] = $originalFileName;
    }

    if ($newFiles != $article_images){
      $images->delete();
    }

Advertisement

Answer

You just can’t delete from database without making a query.

You will have to make new request like this:

Media::where('article_id', $article->id)->delete();

It’s just one simple query, so there shouldn’t be any performance penalty.

If we are talking about collection with 100’s of items, you can optimize the query like this:

Media::whereIn('id', $images->pluck('id'))->delete(); 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement