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

前端 未结 4 648
无人及你
无人及你 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:12

    If the relationship of your database does not go any further than only one layer, then you could simply use Laravel events to handle your soft-deletes within the Model boot() method as follow:

    payments()->delete();
    
            }); 
        }
    

    If, however, your structure goes deeper than only one layer, you will have to tweak that piece of code.

    Let's say for example you don't want to remove the payments of an invoice but rather the whole payment history of a given user.

    {$relation}()->get() as $item) {
                        $item->delete();
                    }
                }
            });
    
            static::restoring(function($resource) {
                foreach (static::$relations_to_cascade as $relation) {
                    foreach ($resource->{$relation}()->get() as $item) {
                        $item->withTrashed()->restore();
                    }
                }
            });
        }
    
        public function payments()
        {
            return $this->hasMany(Payment::class);
        }
    }
    

    {$relation}()->get() as $item) {
                        $item->delete();
                    }
                }
            });
    
            static::restoring(function($resource) {
                foreach (static::$relations_to_cascade as $relation) {
                    foreach ($resource->{$relation}()->get() as $item) {
                        $item->withTrashed()->restore();
                    }
                }
            });
        }
    
        public function invoices()
        {
            return $this->hasMany(Invoice::class);
        }
    }
    

    This paradigm ensures Laravel to follow the rabbit hole no matter how deep it goes.

提交回复
热议问题