Reputation: 3157
I am trying to delete all related rows in Laravel with:
$customers = Customer::find($clientId);
$customers->delete();
$customers->locations()->delete();
$customers->locations->objects()->delete();
$customers->locations->objects->subscriptions()->delete();
$customers->locations->objects->history()->delete();
And also tried:
$customers = Customer::find($clientId);
$customers->delete();
$customers->locations()->delete();
$customers->locations()->objects()->delete();
$customers->locations()->objects()->subscriptions()->delete();
$customers->locations()->objects()->history()->delete();
Laravel deletes the customer and locations but does not delete the objects, subscriptions and history and trows an error.
What can I do to delete them too?
EDIT: I changed the order like this:
$customers = Customer::find($clientId);
$customers->locations()->objects()->subscriptions()->delete();
$customers->locations()->objects()->history()->delete();
$customers->locations()->objects()->delete();
$customers->locations()->delete();
$customers->delete();
and get the error Call to undefined method Illuminate\Database\Query\Builder::objects()
Upvotes: 0
Views: 1674
Reputation: 2426
When you say
$customers->locations()->delete()
you are trying to delete a Collection
. You should delete a Model
.
So get all the locations using
$locations = $customer->locations
and then use a foreach
loop to delete each location
.
foreach($locations as $location) {
$location->delete();
}
Similarly delete all other related models.
Upvotes: 0
Reputation: 4321
you need to override delete method in model to delete all related objects for each location and also delete should be in order, so first delete objects, then locations and then customer. for ex.
$customers = Customer::find($clientId);
$customers->locations()->delete();
now for delete location override delete method in you model something like
class Location extends Model {
public function delete() {
$this->objects()->delete();
parent::delete();
}
}
//also delete hierarchy in your object model with overriding delete method
class Object extends Model {
public function delete(){
$this->history()->delete();
$this->subscriptions()->delete();
parent::delete();
}
}
Upvotes: 2
Reputation: 187
Most likely to do in the reverse order.
If you removed the "parent", the "children", he can not find.
Try this.
$customers = Customer::find($clientId);
$customers->locations()->objects()->subscriptions()->delete();
$customers->locations()->objects()->history()->delete();
$customers->locations()->objects()->delete();
$customers->locations()->delete();
$customers->delete();
Upvotes: 0