Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have this invoices table that which has the following structure

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

and a payments table with the following structure

id | invoice_id | amount | deleted_at 2    2            1000   | NULL 

Invoice Model

class Invoice extends Model {      use SoftDeletes;  } 

here's the code to delete the invoice

public function cance(Request $request,$id) {     $record = Invoice::findOrFail($id);     $record->delete();     return response()->json([         'success' => 'OK',     ]); } 

Payments model

class Payment extends Model {      use SoftDeletes;  } 

The softDelete on Invoice table works perfectly but its related records (payments) still exists.How do I delete them using softDelete?

like image 503
user3407278 Avatar asked Aug 23 '15 05:08

user3407278


People also ask

How can get soft deleted data in laravel?

So By default Laravel Eloquent excludes all the soft deleted records from query results. But you can get also soft deleted record using withTrashed() of Laravel Eloquent. It will return all record from table. Item::withTrashed()->get();

What is the advantage of soft delete in laravel?

The advantage of soft-delete concept is, as you never physically delete the data, there is no risk of loss of data when something goes wrong (with the delete action, not with your code). It's easy to get back the record by just changing the flag.

How do you delete many relationships in laravel?

To delete a model directly, call delete() on it and don't define a deleting listener in its boot method or define an empty deleting method. If you want to further delete relations of a related model, you will define a deleting listener in the boot method of that model and delete the relations there.


1 Answers

Eloquent doesn't provide automated deletion of related objects, therefore you'll need to write some code yourself. Luckily, it's pretty simple.

Eloquent models fire different events in different stages of model's life-cycle like creating, created, deleting, deleted etc. - you can read more about it here: http://laravel.com/docs/5.1/eloquent#events. What you need is a listener that will run when deleted event is fired - this listener should then delete all related objects.

You can register model listeners in your model's boot() method. The listener should iterate through all payments for the invoice being deleted and should delete them one by one. Bulk delete won't work here as it would execute SQL query directly bypassing model events.

This will do the trick:

class MyModel extends Model {   protected static function boot() {     parent::boot();      static::deleted(function ($invoice) {       $invoice->payments()->delete();     });   } } 
like image 135
jedrzej.kurylo Avatar answered Sep 19 '22 08:09

jedrzej.kurylo