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

Wednesday, February 16, 2022

[FIXED] Laravel, copy row to another table with eloquent relationship

 February 16, 2022     laravel-5, php     No comments   

Issue

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.


Solution

You are trying to run the save method on the array but what you want is to use it on the array index instead.

Change your foreach to this and it should work (assuming columns are the same).

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

You can shorten this by using forceCreate.

foreach($_getPOProducts as $i => $_getPOProduct)
{
    $POProduct[$i] = (new DeliveryOrderProducts())->forceCreate($_getPOProduct->only(['order_id', 'item_id', 'qty']));
}


Answered By - Marwelln
  • 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