Search code examples
phplaravel-5.4laravel-bladelaravel-collection

Laravel access collection elements within another iterator


I have db table LovColumnComments and it contains:

----------------------------------------------------
| id | view          | column       | description  |
----------------------------------------------------
| 1  | my_view       | object_id    | Object ID    |
| 2  | my_view       | description  | Description  |
----------------------------------------------------

I have another table DataTable that contains actual data.

-------------------------------------
| id |  object_id    | description  |
-------------------------------------
| 1  |  OBJ_01       | Object 01    |
| 2  |  OBJ_02       | Object 02    |
-------------------------------------

Both these tables are passed to the blade view as collections.

Blade template I have right now is:

<table>
  <thead>
     <tr>
        @foreach ($columns as $column)
          <th>{{$column->description}}</th>
        @endforeach
     </tr>
   </thead>
   <tbody>
      @foreach ($data as $datum)
        <tr>
          <td>{{$datum['object_id']}}</td>
          <td>{{$datum['description']}}</td>
        </tr>
      @endforeach
   </tbody>
</table>

I would like to know whether can I access $data collection instead of using $datum['object_id'] and $datum['description']. This is because, DataTable can be any db table so that field names can be be different but always there will be two columns.

Therefore, $data collection will always have two columns, but column names can be different. I need a more dynamic way of getting column names out of $columns collection.

Something like, <td>{{$columns[0]}}</td> and <td>{{$columns[1]}}</td>

FYI, column of $columns contains the actual names (i.e. object_id and description)

Thanks


Solution

  • So here is my example of how I would do this in my blade view:

    @if(count($data) > 0)
        @php
            $keys = array_keys($data[0]);
        @endphp
        @foreach($data as $d)
            @foreach($keys as $key)
                <!-- This is the dynamic value that works with any array -->
                {{$d[$key]}}
            @endforeach
        @endforeach
    @endif
    

    Let me know if you have any questions, I will happily try and help!