mercredi 3 août 2016

Updating related model attributes on delete

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire