在Laravel的Eloquent中嵌套循环

I am having trouble with my code. I have two tables Stocks and StockLists however, I want to get all the related stock in the stocks list based on the stock code. But the result is repeated in each stocks.... Here is the link of the image https://www.screencast.com/t/rHdT2gigh

public function index()
{
    $stocks = Stock::all();
     foreach ($stocks as $stock) {
        $stockInfos = DB::table('stocksList')
        ->where('stockCode', $stock->stockCode)
        ->take(3)
        ->get();
     }
     return view('welcome', compact('stocks', 'stockInfos'));
}

Here is my blade.php

@forelse($stocks as $stock)
                    <tr align="left">
                        <th scope="row">{{ $stock->stockCode }}</th>
                        <td><strong>{{ $stock->stockName }}</strong></td>
                        <td><strong>
                            @forelse($stockInfos as $stockInfo)
                            {{ $stockInfo->stockDate }} : {{ $stockInfo->stockPrice }}
                            <br>
                            @empty
                            <em>No Data</em>
                            @endforelse                            
                        </strong></td>    
                    </tr>
                    @empty
                    @endforelse

You are overwritting the $stockInfos variable try with

public function index()
{
    $stocks = Stock::all();
    $stockInfos = [];
     foreach ($stocks as $stock) {
        array_push($stockInfos,DB::table('stocksList')
        ->where('stockCode', $stock->stockCode)
        ->take(3)
        ->get());
     }
     return view('welcome', compact('stocks'))->with('stockInfos',collect($stockInfos));
}

And in your view :

@forelse($stocks as $stock)
      <tr align="left">
          <th scope="row">{{ $stock->stockCode }}</th>
          <td><strong>{{ $stock->stockName }}</strong></td>
          <td><strong>
                            @forelse($stockInfos->where('stockCode',$stock->stockCode) as $stockInfo)
                            {{ $stockInfo->stockDate }} : {{ $stockInfo->stockPrice }}
                            <br>
                            @empty
                            <em>No Data</em>
                            @endforelse                            
                        </strong></td>    
                    </tr>
                    @empty
                    @endforelse

Try this :

$stockInfos = DB::table('Stock')
             ->join('stocksList','stocksList.stockCode','=','Stock.stockCode')
             ->get();