Support the ongoing development of Laravel.io →
Database Views Blade

This probably isn't the most elegant solution but so far I have my data/collection called like so;

$payments = Payment::all()->toArray();

return view('contracts.show')
		->with('payments', $payments);

My show.blade.php is;

<table class="table table-striped table-bordered">
@foreach($payments as $key => $array)

	<tr>
	@foreach($array as $column_name => $value)
		<th><strong>{{ $column_name }}</strong></th>
	@endforeach
	</tr>			

	<tr>
	@foreach($array as $column_name => $value)
		<td>{{ $value }}</td>
	@endforeach
	</tr>
@endforeach
</table>

This means I end up having the field/column names from my table printed out for every row in my table. Obviously, I only want it once - at the top.

Is there a blade solution to this? I am using toArray() because my column names have spaces in them eg Column One (if that makes a difference to your answer).

If I pass $i as '1' then I could do something like;

<?php if($i == '1') { ?>
<tr>
@foreach($array as $column_name => $value)
	<th><strong>{{ $column_name }}</strong></th>
@endforeach
</tr>	

<?php $i = '0'; ?>

<?php } ?>	

But that doesn't seem very..... Laravel.

Last updated 3 years ago.
0
Solution

Not quite sure I got your problem, but I think you want something like this:

<table class="table table-striped table-bordered">
  <tr>
  @foreach(array_keys($payments[0]) as $column_name)
      <th><strong>{{ $column_name }}</strong></th>
  @endforeach
  </tr>

@foreach($payments as $payment)
    <tr>
    @foreach($payment as $value)
        <td>{{ $value }}</td>
    @endforeach
    </tr>
@endforeach
</table>
Last updated 10 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mikelovely mikelovely Joined 26 Mar 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.