moses's avatar
Level 2

How can I display dinamyc key of array in the laravel blade?

My controller like this :

public function index(Request $request)
{
    $param = $request->all();
    $data = $this->itemDetailRepository->getData($param);
    return view('item-detail.index', compact('param'))
        ->withItems(count($data)>0?$data:null);
}

If I debug $data or in laravel (dd($data)), the result like this :

enter image description here

So the array $data is collection and pagination like that

If I click in the attributes section, it display like this :

#attributes: array:5 [▼
  "item_number" => "AB-0001"
  "total_quantity" => "1000"
  "location-a" => "500"
  "location-b" => "500"
]

So the array data is there

In the view blade laravel like this :

<table>
    <tr>
        <th>ITEM NUMBER</th>
        <th>TOTAL QUANTITY</th>
        <th>LOCATION-A</th>
        <th>LOCATION-B</th>
    </tr>
        @foreach($items as $item)
        <tr>
            <td>{{ $item->item_number }}</td>
            <td>{{ $item->total_quantity }}</td>
            <td>{{ $item['location-a'] }}</td>
            <td>{{ $item['location-b'] }}</td>
        </tr>
        @endforeach
</table>

It works. But my key of the array is dynamic. The key can change

So the array can change like this :

#attributes: array:5 [▼
  "item_number" => "AB-0001"
  "total_quantity" => "500"
  "location-a" => "500"
]

Or can change like this :

#attributes: array:5 [▼
  "item_number" => "AB-0001"
  "total_quantity" => "1500"
  "location-a" => "500"
  "location-b" => "500"
  "location-c" => "500"
]

So the location is dynamic

How do I set it in the laravel view blade so that it can adjust to dynamic arrays?

0 likes
3 replies
burlresearch's avatar

You have an array-of-arrays, and the nested array may have a variety of keys. The hint here is that you have 2-deep arrays, so use 2 for-loops. To get what you want you could try:

@foreach($items as $row)
    <ul>
        @foreach($row as $attr => $valu)
            <li><strong>{{ $attr }} :</strong> {{ $valu }}</li>
        @endforeach
    </ul>
@endforeach

rendering this as a table is a poor choice, since, as you know, you will have a different number of columns foreach, though it can be done.

This will get your data out - you can play around with how you finally render it.

moses's avatar
Level 2

@burlresearch There exist error htmlspecialchars() expects parameter 1 to be string, array given

burlresearch's avatar

That should give you the basic idea - but that approach is how you can do it.

Please or to participate in this conversation.