Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Deleting related models one-to-many in Laravel

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.