Foreach在laravel中使用不同的查询调用一个数据库表中的值

Foreach在laravel中使用不同的查询调用一个数据库表中的值

问题描述:

I want to retrieve values ​​from one database table but separated in two adjacent tables based on different id_produk (foreign key) values.

This is code in Controller :

public function index()
{
  $item_ict  = Item::where('id_produk', '1');
  $item_cm   = Item::where('id_produk', '2');

  return view('item/index', compact('item_ict', 'item_cm'));
}

Then, I call $item_ict and $item_cm in index

<table class="table">
  <thead>
    <tr>
      <th>ICT</th>
      <th>CM</th>
    </tr>
  </thead>
  <tbody>
    @foreach ($item_ict as $itemict)
    @foreach ($item_cm as $itemcm)
    <tr>
      <td>{{ $itemict -> nama_item }}</td>
      <td>{{ $itemcm -> nama_item }}</td>
    </tr>
    @endforeach
    @endforeach
  </tbody>
</table>

is it the correct way when i wrote that foreach? Nothing errors, but no values exited. How the way to fix it?

Or i'm thinking about call it use query in index page, but i dont know how. is it possible? how?

Combine your items into one array so that you only need to do one loop.

Also, use ->get() to actually get the items. As it stands, your code is still just the query builder.

public function index()
{
    $all = [];
    $item_ict = Item::where('id_produk', '1')->get();
    $item_cm = Item::where('id_produk', '2')->get();

    for ($i = 0; $i < max($item_ict->count(), $item_cm->count()); $i++) {
        $all[] = [
            isset($item_ict[$i]) ? $item_ict[$i] : null,
            isset($item_cm[$i]) ? $item_cm[$i] : null,
        ];
    }

    return view('item/index', compact('all'));
}

<table class="table">
    <thead>
        <tr>
            <th>ICT</th>
            <th>CM</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($all as $items)
            <tr>
                <td>{{ $items[0] ? $items[0]->nama_item : null }}</td>
                <td>{{ $items[1] ? $items[1]->nama_item : null }}</td>
            </tr>
        @endforeach
    </tbody>
</table>