Ad

Iterate Over Columns Blade Laravel

- 1 answer

I want to loop through values of all columns and print it on table. But can't do it. Below my controller:

$resultpersonel = DB::table('puantajs')
    ->leftJoin('personnels', 'puantajs.pPersonel', '=', 'personnels.id')
    ->select('personnels.sAd','personnels.sSoyad','personnels.sGorev','puantajs.*')
    ->where('puantajs.nYear', $yearresult)
    ->where('puantajs.nMonth', $monthresult)
    ->where('puantajs.pPersonel', $personel)
    ->get();

Below my blade code : first i get how many rows are there. second i iterate over each column and print value. This is one of the basic and standart code block. But laravel gets it so complicated.

@foreach($resultpersonel as  $data)

            @for ($i = 0; $i <'30'; $i++)                                               
            <td id="r">{{$data[$i]}}</td>                                                                                         
            @endfor            
            </tr>
   @endforeach

It gives error :

Cannot use object of type stdClass as array

Ad

Answer

You cannot access the elements of an object by a numeric index. You have to cast the model to an array and use a foreach:

<table class="table table-bordered">
    @foreach ($resultpersonel as $data)
        <tr>
            @foreach ($data->toArray() as $column => $value)
                <td>{{ $column }}</td>
                <td>{{ $value }}</td>
            @endforeach
        </tr>
    @endforeach
</table>
Ad
source: stackoverflow.com
Ad