phplaravel-5

How to delete parent table's data when all related child rows form child table are deleted?


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!