Reputation: 12708
Using Laravel 5.1, I want to soft delete a category
, which should automatically set attributes on its related models, question
.
This SO Post recommends binding delete event on the model:
public function destroy(Category $category)
{
$category->delete();
}
Then...
protected static function boot() {
parent::boot();
static::deleting(function($category) {
$category->questions()->delete();
});
}
This works. But I don't want to delete the related questions, rather set an attribute on each:
static::deleting(function($category) {
$category->questions()->is_published = 'no';
});
This doesn't seem to work. There is no error, but also no queries are fired in my query logger. Why is delete()
fired on each related model, but not attribute changes?
The way I get this to work now is as such, but it's not clean:
static::deleting(function($category) {
$questions = $category->questions()->get();
foreach($questions as $q) {
$q->is_published = 'no';
$q->save();
}
});
Upvotes: 3
Views: 272
Reputation: 196
You could do something like this
In your question model
public function setIsPublished($isPublished) {
$this->is_published = $isPublished;
return $this;
}
And change
static::deleting(function($category) {
$questions = $category->questions()->get();
foreach($questions as $q) {
$q->is_published = 'no';
$q->save();
}
});
to
static::deleting(function($category) {
foreach($category->questions as $q) {
$q->setIsPublished('no')->save();
}
});
Upvotes: 1