Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - delete whole collection

Tags:

php

laravel

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();     } 
like image 223
Ludwig Avatar asked Jun 30 '16 10:06

Ludwig


People also ask

How to delete Laravel collection?

To delete a whole model collection in Laravel you can make use of the "delete()" method on the collection instance itself. Imagine you have a post and you want to delete the one with an id of 1, 2, 3, 4, 5 then you can write your code like below. <? php Post::query() ->whereIn('id', [1, 2, 3, 4, 5]) ->delete();

How do I delete all records in laravel?

In the first example, we are going to use the truncate() function, which is used to delete all the records. In the second example, we will delete records on the basis of the id. So we will specify some id and use the delete() function to delete all the records of that particular id.

How do I delete data in laravel?

Laravel Eloquent Deleting You can delete data after writing it to the database. You can either delete a model instance if you have retrieved one, or specify conditions for which records to delete. To delete a model instance, retrieve it and call the delete() method: $user = User::find(1); $user->delete();


1 Answers

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();  
like image 113
Sigismund Avatar answered Sep 28 '22 11:09

Sigismund