How to soft delete related records when soft deleting a parent record in Laravel?

前端 未结 4 673
无人及你
无人及你 2021-02-04 01:36

I have this invoices table that which has the following structure

id | name | amount | deleted_at
2    iMac   1500   | NULL

and a payments tabl

4条回答
  •  忘掉有多难
    2021-02-04 02:35

    You can go one of 2 ways with this.

    The simplest way would be to override Eloquents delete() method and include the related models as well e.g.:

    public function delete()
    {
        $this->payments()->delete();
        return parent::delete();
    } 
    

    The above method should work just find but it seems a little bit dirty and I'd say it's not the preferred method within the community.

    The cleaner way (IMO) would be to tap into Eloquents events e.g.:

    public static function boot()
    {
        parent::boot();
    
        static::deleting(function($invoice) { 
             $invoice->payments()->delete();
    
        });
    }
    

    Either (but not both) of the above methods would go in your Invoice model. Also, I'm assuming that you have your relationships set up in your model, however, I'm not sure if you allow multiple payments for one invoice. Either way you might need to change the payments() in the examples to whatever you've named the relationship in your invoice model.

    Hope this helps!

提交回复
热议问题