Home > Back-end >  laravel get() return 2 rows but foreach gives only the last row()
laravel get() return 2 rows but foreach gives only the last row()

Time:04-17

  • 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

  • Get() result:

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

  • Foreach loop output

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

CodePudding user response:

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);

CodePudding user response:

thanks every one for your answer. I solved it following way:

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

CodePudding user response:

You are replacing array so its storing last data

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

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

dd($data);

if you need id as key then

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

or

$data[]['id']= $odetail->product_id; 

or Simple way is to use pluck

$orderdetail = DB::table('order_details')->where('order_id',$eid)->pluck('product_id');
  • Related