Ronnie
Ronnie

Reputation: 39

Laravel-Mediable - delete media together with file

I've been reading the Laravel-Mediable docs about deleting media.

However, I'm a bit confused on how to delete a specific media, together with its file without using query builder. As per the docs,

Note: The delete() method on the query builder will not delete the associated file. It will still purge relationships due to the cascading foreign key.

Upvotes: 0

Views: 553

Answers (1)

Sean Fraser
Sean Fraser

Reputation: 352

Author of laravel-mediable here.

The reason for this is that when a mediable model's delete() method is called, we are able to hook into that behaviour to clean up the file from the disk. However, when the delete() method of the query builder is called, it simply runs a DELETE FROM ... SQL query on the database without notifying any other part of the application.

The easiest way to delete models matching a query along with their files is to perform a select query first, then delete the models one by one.

$results = Media::where(...)->get();
$results->each(function($media) {
    $media->delete();
});

Granted, that results in N+1 queries. I will make note to add a better mass deletion method to the todo list for the next version.

Upvotes: 2

Related Questions