The issue is that you're callingdelete()
on a Collection, which does not have that method.
You have a couple options here.
Model Events
If you have event listeners for thedeleting
/deleted
model events, you will need to make sure the deletion happens in a way that each model is loaded and then deleted.
In this case, you can use thedestroy
method on the model that takes a list of ids. It will load a new model for each id, and then calldelete()
on it. As you mention in a comment, it won't restrict the deletion to only those products in the organization, so you would need to filter out those ids before passing the list into thedestroy()
method.
public function destroy($id)
{
try {
$ids = explode(",", $id);
// intersect the product ids for the org with those passed in
$orgIds = array_intersect($org->products()->lists('id'), $ids);
// now this will only destroy ids associated with the org
\App\Product::destroy($orgIds);
}
catch(...) {
}
}
If you don't particularly like that approach, you will need to iterate your collection of organization products and calldelete()
on them individually. You can use a standardforeach
, or you can use theeach
method on the collection:
public function destroy($id)
{
try {
$ids = explode(",", $id);
$org->products()->find($ids)->each(function ($product, $key) {
$product->delete();
});
}
catch(...) {
}
}
No Model Events
Now, if you don't have any model events that you need to listen for, things are a little easier. In this case, you can just calldelete()
on the query builder, and it will go straight to deleting the records without loading any model objects. So, you get cleaner code with better performance:
public function destroy($id)
{
try {
$ids = explode(",", $id);
// call delete on the query builder (no get())
$org->products()->whereIn('id', $ids)->delete();
}
catch(...) {
}
}
destroy()
Model::destroy
orgs
organization
delete
$org->products()->find($ids)->each(function($product){ $product->delete(); });