How do delete parent and child records from the table in Laravel?

In this tutorial, I will give you an example of “Laravel delete one to many relationship“, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9.

Deleting related models one-to-many in Laravel

Sometimes we have two tables and we have one to many relationships between them in the Laravel application.

For example, we have a posts and comments table and we have a foreign key post_id column in the comments table.

delete related id record in another table in laravel

When we store post data in the posts table and we also store post comments in the comments table and we have the post table primary key as a post_id in the comments table as a foreign key in our Laravel application.

Let’s see an example of Laravel deleting one to many relationships

In this given below example, If we want to delete any post then the related post comments records are also deleted from the comments table.

Recommended Article:- Laravel Foreign Key.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Comment;


class PostController extends Controller
{
  public function Delete($id){
     $return = Post::where('id', $id)->delete();
     if($return){
      Comment::where('post_id', $id)->delete();
      return response()->json(['status'=>'Post and Post Comments has been deleted successfully']);
    }
}

In this article, we learned an example of “Laravel delete one to many relationship and How do delete parent and child records from the table in Laravel”, I hope this article will help you with your Laravel application Project.

Read also:- One To One Relationship in Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com

Scroll to Top