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

1.8k views Asked by At

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

1

There are 1 answers

0
Niraj Shah On BEST ANSWER

Change your second @foreach to be:

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