Geoff_S
Geoff_S

Reputation: 5107

using an array for an html table in laravel

I'm getting undefined index errors on my blade when trying to take my array and plug the values into an html table structure.

I have the array looped and sending it to blade:

Controller

$result = array();
foreach($getItem as $Item){
    $result[$Item->item_id][] = $Item;
}

//returning to blade but not included here

Dumped array:

array:26 [▼
    11873 => array:2 [▼
        0 => {#407 ▼
          +"item_id": "11873"
          +"item_name": "Title"
          +"item_comment": "Item Title"
          +"item_type": "2"
        }
        1 => {#408 ▼
          +"item_id": "11873"
          +"item_name": "Instruction"
          +"item_comment": "Inst Comment"
          +"item_type": "2"
        }
]

Blade:

@foreach ($result as $id => $item)
    <tr>
        <td>{{ $item['item_id'] }}</td>
        @if($item['item_name'] == "Title")
            <td>{{ $item['item_comment'] }}</td>
        @endif
        <td>{{ $item['item_type'] }}</td>
    </tr>
@endforeach

So with the dumped array structure, one issue is the fact that the 'item_type' should be at the high level with the id, and shouldn't be in each nested level. But other than that I get undefined index errors. Am I just looping incorrectly?

Upvotes: 0

Views: 839

Answers (1)

Rehmat
Rehmat

Reputation: 5071

In @foreach ($result as $id => $item), $item is an array and you need to loop over it as well.

@foreach ($result as $id => $item)
    <tr>
        <td>{{ $id }}</td>
        @foreach($item as $subitem)
        @if($subitem['item_name'] == "Title")
            <td>{{ $subitem['item_comment'] }}</td>
        @endif
        <td>{{ $subitem['item_type'] }}</td>
        @endforeach
    </tr>
@endforeach

Upvotes: 1

Related Questions