Search code examples
phplaravelloopsforeachforeach-loop-container

How to run two foreach loop inside one html table in Laravel?


I want to show two foreach loop data dynamically inside one table, but the design of the table break after dynamic loop data. My blade.php code is given below:

<table>
  <tr>
     <th>Name</th>
     <th>Buy Rate</th>
     <th>Sell Rate</th>
  </tr>
  <tr>
   <?php foreach($datav as $data){ ?>
     <td><?php echo $data->name; ?></td>
     <td><?php echo $data->buy_rate; ?></td>
   <?php } ?>
  <?php foreach($sells as $sell){ ?>
     <td><?php echo $sell->rate; ?></td>
  </tr>
  <?php } ?>
</table>

My route is:

Route::get('/','WelcomeController@test');

My Controller Code:

public function test(){

$datav= DB::table('localcurrency')
              ->where('status',1)
              ->get();
$sells= DB::table('localcurrency2')
              ->where('status',1)
              ->distinct()
              ->get();

return view('home.home_content')
        ->with('datav',$datav)
        ->with('sells',$sells);

}

How can I run this?


Solution

  • It is better if you merge both $datav and $sells in one array.

    In this above scenario firstly your $datav array will complete then it goes to second array.

    So it will not create a complete table. Or the table alignment will be wrong.

    Rest depends on what you proceed in the array.

    public function test(){
    
    $datav= DB::table('localcurrency')
              ->where('status',1)
              ->get();
    $sells= DB::table('localcurrency2')
              ->where('status',1)
              ->distinct()
              ->get();
    $sells=$sells->toArray();
    $results=array();
    foreach($datav as $key=>$data)
    {
       $newarr=array();
       $newarr['name']=$data->name;
       $newarr['buy_rate']=$data->buy_rate;
       $newarr['sell_rate']=$sells[$key]->rate;
       $results[]=$newarr;
    }
    return view('home.home_content')
        ->with('results',$result);
    
    }
    

    Your views looks like this

    <table>
       <tr>
        <th>Name</th>
        <th>Buy Rate</th>
        <th>Sell Rate</th>
       </tr>
       @foreach($results as $result)
         <tr>
             <td>{{$result['name']}}</td>
             <td>{{$result['buy_rate']}}</td>
             <td>{{$result['sell_rate']}}</td>
        </tr>
      @endforeach