/** * Deletes a model that was formerly related to this model. * This performs a check to see if the model is at least not being used * for the same type of relation by another model. Note that this is not * safe by any means -- use on your own risk. * * @param Model $model * @param RelationInfo $info */ protected function deleteFormerlyRelatedModel(Model $model, RelationInfo $info) { $class = $this->modelClass; // To see if we can safely delete the child model, attempt to find a different // model of the same type as the parent model, that has a relation to the child model. // If one exists, it's still in use and should not be deleted. /** @var Model $class */ $inUse = $class::whereHas($info->relationMethod(), function ($query) use($model, $info) { /** @var \Illuminate\Database\Eloquent\Builder $query */ $query->where($info->model()->getTable() . '.' . $info->model()->getKeyName(), $model->id); })->where($this->model->getTable() . '.' . $this->model->getKeyName(), '!=', $this->model->id)->count(); if ($inUse) { return; } $model->delete(); }