Search code examples
laravel-5foreach-loop-container

Get columns names and value of table created on runtime using Laravel


How to get column names and value of a table created on runtime with laravel.

$table = 'table_name';
$columns = DB::getSchemaBuilder()->getColumnListing($table);
$records = DB::table($table)->get();

Now i get can column name by this in view.

 <tr>
   @for($i = 0; $i < sizeof($columns); $i++)
     <th>{{ ucfirst(str_replace('_', ' ',$columns[$i]) )}}</th>
   @endfor
</tr>

Now how can i display column values below column headings

@foreach($records as $key=>$row)

 {{ $row->id}}

@endforeach

I need this type of output

Table Name

id | colum_1 |colum_2 | etc

1 | test | test11

2 | asdf | asf


Solution

  • Change your second @foreach to be:

    @foreach($records as $row)
      <tr>
        @foreach($row as $data)
          <td>{{ $data }}</td>
        @endforeach
      </tr>
    @endforeach