Laravel - Delete with all relations

11,599

If you are using MySQL (or any RDBMS which supports cascading) you can cascade deleting on database level. If don't, you have to handle it manually on controller or by model event listening functions. See documentation on migrations detailing foreign key constrains.

Schema::create('order_items', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('order_id');
    $table->timestamps();

    $table->foreign('sell_order_id')
          ->references('id')
          ->on('orders')
          ->onDelete('cascade');
});

Note: Laravel supports soft deletes out of the box, as well as cascading soft deletes, see following article https://laravel-news.com/cascading-soft-deletes-eloquent

Share:
11,599
Admin
Author by

Admin

Updated on June 22, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a system where a user is connected to alot of different tables, These tables are also connected to different tables. When I delete a user from my database, every relation associated with that user should also be deleted. My project's relation setup looks like this

    - A User user has multiple orders.
    - An Order has multiple order items.
    - Order Items belong to an order.
    - A webshop belongs to a user and a webshop has One Main Setting.
    - Main settings belongs to a webshop and has One address.
    - Address belongs to main setting
    

    When a user with the id of 1 gets deleted. All orders where the user_id is equal to 1 should also be deleted, No problems there. But the order with the user_id of 1 also has Many order_items. So say for instance this particular order has the id of 3. All order_items with the order_id of 3 should also be deleted. And that is where I ran into this issue.

    My attempt

    A user gets deleted by doing this

    $user = User::find($id);
    $user->delete();
    

    A relation gets deleted by doing this:

    $user->orders()->delete();
    

    But how do I delete the order items associated with all the orders that get deleted? My attempt was:

    $user->orders()->orderitems()->delete();
    

    But unfortunately, that does not work. All the relations in the models are working perfectly fine. So all properties that are useable are

    User
    - Orders();
    - Webshops();
    Order
    - Orderitems();
    Webshop
    - Mainsetting();
    Mainsetting
    - Address();
    

    How can I accomplish the above?

  • train_fox
    train_fox almost 6 years
    Laravel also supports cascading fo soft deletes: laravel-news.com/cascading-soft-deletes-eloquent
  • Kyslik
    Kyslik almost 6 years
    Could you add an example migration, it would add value to the answer.
  • DCTID
    DCTID about 4 years
    Welcome to SO and thanks for answering! I think your answer would be more helpful to the community if you included an example or explained why your suggestion would work.