AKmahato
8 months ago
129
4
Laravel

How to insert multiple records in child table

Posted 8 months ago by AKmahato

I have two tables Category and SubCategory I want to insert data in both tables from one single form but while inserting I want to insert multiple records in the child table. Insertion is happening but only in the parent table no data inserting in the child table.


Here is my code
--------------------------

public function store(Request $request)
    {
        //print_r($request);
        //dd($request);

        $category = new AddCategory();

        $category->c_date = $request->c_date;
        $category->c_name = $request->c_name;
        $category->c_desc = $request->c_desc;
      
        $category->save();

 $sc_name = $request->input('sc_name');
        $sc_desc = $request->input('sc_desc');

        $n = count($sc_name);
        dd($n);

        $subcategory = [];

        for($i=0; $i<$n; $i++){
            $data=[
                'sc_name' => $sc_name[$i],
                'sc_desc' => $sc_desc[$i],
                'cat_id' => $category->id 
            ];

            $subcategory[]=$data;
        }

        foreach($subcategory as $row){
            AddSubCategory::create($row);
        }
        return redirect()->back();


Please sign in or create an account to participate in this conversation.