Reputation: 155
I'm making an app that could (soft) delete a post. It will delete the record on database and delete image file on storage, I tried to create an override method for delete()
in my model and it looks like this
public function delete()
{
$tempImage = $this->image;
parent::delete();
$this->imageDelete($tempImage);
}
public function imageDelete($image)
{
$this->image = null;
$this->save();
if (! empty($image)) {
unlink(public_path() . self::$pathImage . $image);
unlink(public_path() . self::$pathThumb . $image);
}
}
It works for deleting one record. But, when I try to delete multiple record (using whereIn
), the override method is not accessed, and the whereIn
is accessing the real delete()
method.
This is my controller for delete posts
public function delete(Request $r)
{
Message::findOrFail($r->id)->delete();
return redirect()->back();
}
public function multipleDelete(Request $r)
{
Message::whereIn('id', $r->select)->delete();
return redirect()->back();
}
If I delete the records with multipleDelete()
, It only delete the record on database.
Upvotes: 1
Views: 1871
Reputation: 1745
What delete()
that you override is actually Eloquent model delete. However, when you tried to delete directly after whereIn()
, it is DB query. So it won't go through your model at all. It is using raw sql to delete the data.
What you can do is retrieve the result as Eloquent model first, then loop to delete.
Message::whereIn('id', $r->select)->get()->each(function($msg) {
$msg->delete();
});
Upvotes: 4