Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

laravel get() return 2 rows but foreach gives only the last row()

  • in order details table i have 2 row . When I use get() it gives 2 rows. But in foreach loop it only gives the last row.

In Controller:

$orderdetail = DB::table('order_details')->where('order_id',$eid)->get();

print_r($orderdetail);


$data =array();
foreach($orderdetail as $odetail){
    $data['id']                 = $odetail->product_id;
 }

dd($data);

output:

following is the output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • Get() result:

    [0] (
    [id] => 832
    [product_id] => 1090
    )
    [1] (
    [id] => 833
    [product_id] => 1133
    )

  • Foreach loop output

    array:1 [▼
    "id" => 1133
    ]

>Solution :

You overwrite in $data[‘id’] in foreach loop ,so it has one member
,you can use one of this code:

$data =array();
foreach($orderdetail as $key=>$odetail){
    $data[$key]['id']= $odetail->product_id;
 }
dd($data);

OR

$data=DB::table('order_details')->where('order_id',$eid)->get()->pluck('product_id);

OR

$data =array();
$i=0
foreach($orderdetail as $odetail){
    $data[$i++]['id']= $odetail->product_id;
}
dd($data);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading