3

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();
        }
    });
Community
  • 1
  • 1
user3871
  • 12,432
  • 33
  • 128
  • 268
  • if you want to set attribute you will need to save it. You can use local scope in question model to fire one query changing all questions with a specific category id – ClearBoth Aug 03 '16 at 23:43

1 Answers1

1

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();
    }
});