PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

[FIXED] Delete parent table data when deleted all related child rows form child table in laravel

 March 01, 2022     laravel-5.5, php     No comments   

Issue

This is my parent table:-

id | name    | created_at
 1 | mobile  |  NULL
 2 | Laptop  |  Null 

And This is Child table:-

id | name  |parent_id| amount | created_at
 1 | Nokia |    1    | 2500   | NULL
 2 |Samsung|    1    | 3500   | Null
 3 |Sony   |    1    | 4000   | Null 

When I am deleting all child data of related by parent Mobile data using by foreign key then I want to delete also Mobile Data in a parent table.


Solution

Add this code after your delete statement

$child = DB::table('child')->where('parent_id',$id)->get();
if($child->count() == 0){
    $parent = DB::table('parent')->where('id', $id)->delete();;
}

Make sure you are using Query builder for this

If you are using eloquent, and not DB, then add ..

use DB;

before the class.

Hope this solves your problem!



Answered By - Krishanu
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing