Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, copy row to another table with eloquent relationship

Tags:

php

laravel-5

I want to get the data form database table and create a new row in another table. Which 1 PO have many PoProducts.

    $_getPO = Order::find($id);
    $_getPOProducts= OrderProducts::where('order_id', $id)->get();

    $order_no = $_getPO->order_no;
    $eta = $_getPO->eta;

    $_Order = new DeliveryOrders();
    $_Order->order_no = $order_no;
    $_Order->eta = $eta;
    $_Order->save();

    $POProduct = array();
    foreach($_getPOProducts as $i => $_getPOProduct)
    {
        $POProduct[] = new DeliveryOrderProducts();
        $POProduct[] = $_getPOProduct->order_id;
        $POProduct[] = $_getPOProduct->item_id;
        $POProduct[] = $_getPOProduct->qty;
        $POProduct->save();
    }

But, this output an error.

   Call to a member function save() on array

Please help me. Thanks.

like image 807
BlackLotus Avatar asked Dec 11 '25 08:12

BlackLotus


1 Answers

If you wish to copy records from one table to another or just duplicate a record in the same table you could simply use the repliacate() method.

        $user = User::findOrFail($id);
        
        // replicate (duplicate) the data
        $staff = $user->replicate();

        // make into array for mass assign. 
        //make sure you activate $guarded in your Staff model
        $staff = $staff->toArray();

        Staff::firstOrCreate($staff);

Note: in case you're only duplicating on the same table replace Staff with User on this example.

like image 106
Waiyl Karim Avatar answered Dec 13 '25 22:12

Waiyl Karim