0

I have two models with a relationship.

So when Model A will be delete, all related Models B should be also delete.

I'm working with soft deleting.

Here my trigger in Model A:

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

    // Delete Relations
    self::deleting(function (Customer $customer) {
        $customer->contacts()->delete();
    });
}

When I delete a Model A the related Models from B will not be touched. So nothing happens.

So the trigger is not working. I got no error or something else. Has anyone an idea how I should find the mistake?

Edit: The relations looks like this:

public function contacts()
{
    return $this->hasMany(Contact::class);
}

and

public function customer()
{
    return $this->belongsTo(Customer::class);
}

In all other cases where I use the relation it works fine.

Markus
  • 1,909
  • 4
  • 26
  • 54

2 Answers2

1

It may be that you need to change your query to complete the relation builder and then delete. Change:

$customer->contacts()->delete();

to:

$customer->contacts->delete();
thisiskelvin
  • 4,136
  • 1
  • 10
  • 17
0

You have to change your migration file

$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');

you can also delete the contacts before delete the customer like this

class Customer extends Eloquent
{
    public function contacts()
    {
        return $this->has_many('Contact');
    }

    public function delete()
    {
        // delete all related contacts
        $this->contacts()->delete();

        // delete the customer
        return parent::delete();
    }
}
Sethu
  • 1,299
  • 10
  • 13