1

I'm looking for a strategy for destroying Eloquent aggregates, e.g. models that "contain" other models.

In Ruby on Rails's ActiveRecord, there is a dependent: :destroyoption that can be placed when defining relations, meaning that if e.g. an order is deleted, then the order_lines must go too.

Is there something similar in Laravel? Or any other alternatives besides manually cleaning up and wrapping it in a transaction?

Niels B.
  • 5,912
  • 3
  • 24
  • 44
  • Have you thought about setting ondelete properly for related tables in DB? – Marcin Nabiałek Oct 16 '14 at 19:44
  • ondelete? Are you talking about database triggers? I don't want to put this kind of logic into the database. – Niels B. Oct 16 '14 at 19:49
  • possible duplicate of [Automatically deleting related rows in Laravel (Eloquent ORM)](http://stackoverflow.com/questions/14174070/automatically-deleting-related-rows-in-laravel-eloquent-orm) – Niels B. Oct 16 '14 at 21:01

1 Answers1

1

If you use Laravel schema builder, you should use foreign key and for foreign key add for example:

$table->foreign('entry_id')
    ->references('id')
    ->on('entries')
    ->onDelete('CASCADE');

You can of course do the same in for example phpMyAdmin.

When using such construction, if in this case record from entries will be deleted, automatically record from this table that have entry_id the same as id from entries that is being delete will be deleted.

It's not a trigger, because trigger are much more complex structure, it's just defining relation and telling what to do if related parent record will be deleted.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • As much as this is a way of doing it, it's not the solution. I'm looking for a way to get Laravel/Eloquent to work. Not my SQL database. – Niels B. Oct 16 '14 at 20:38
  • @NielsB Maybe you want to look at http://stackoverflow.com/questions/14174070/automatically-deleting-related-rows-in-laravel-eloquent-orm then but using `onDelete` is the best option I think without coding – Marcin Nabiałek Oct 16 '14 at 20:54
  • I agree, but I prefer coding. Thanks for the link to the other question. I'm voting to close this as a duplicate. – Niels B. Oct 16 '14 at 21:02