katie hudson
katie hudson

Reputation: 2893

Soft Deleting through relationships

I am trying to understand something.

I have a Project Model.
A Project can have many Document.
A Document has many DocumentData.

So this is straight forward, I have my models set up like so

class Project extends Model
{
    protected $table = 'projects';
    protected $guarded = [];
    use SoftDeletes;

    public function document()
    {
        return $this->hasMany('App\document', 'projectId');
    }

    public static function boot()
    {
        parent::boot();

        static::deleted(function($document)
        {
            $document->delete();
        });
    }
}

class Document extends Model
{
    use SoftDeletes;

    protected $table = 'document';
    protected $guarded = [];

    public function project()
    {
        return $this->belongsTo('App\Project', 'projectId');
    }

    public function documentData()
    {
        return $this->hasMany('App\DocumentData', 'documentId');
    }

    public static function boot()
    {
        parent::boot();

        static::deleted(function($document)
        {
            $document->documentData()->delete();
        });
    }
}

class DocumentData extends Model
{
    use SoftDeletes;

    protected $table = 'document_data';
    protected $guarded = [];

    public function document()
    {
        return $this->belongsTo('App\Document', 'documentId');
    }
}

I am trying to understand the boot function and whether I have set it up properly? When I delete a project, its deleted_at timestamp is set. I am also looking for it to set the deleted at timestamp for all of that Projects Documents and DocumentData.

At the moment, when I delete a Project, on its deleted_at timestamp is set. The Document and DocumentData remains null.

How can I get it soft deleting through all related models?

Thanks

Upvotes: 2

Views: 1139

Answers (1)

jsphpl
jsphpl

Reputation: 5070

You're using the boot method correctly. The only thing i notice is a mistake in the handler of your Project's deleted event. You're trying to delete the instance again after it's been deleted. Instead, i suppose, you want to delete the associated Documents like so:

public static function boot()
{
    parent::boot();

    static::deleted(function($project)
    {
        $project->document()->delete();
    });
}

Alternative Method:

The way i usually delete children is to override the delete() method on the parent models. I prefer the resulting code that way, but that's just a personal preference.

In your case that would be:

class Project extends Model {
    public function delete()
    {
        parent::delete();  // first delete the Project instance itself
        $this->document()->delete();  // delete children
    }
}

class Document extends Model {
    public function delete()
    {
        parent::delete();
        $this->documentData()->delete();
    }
}

Upvotes: 2

Related Questions