Willy Sandi
Willy Sandi

Reputation: 23

How to access prev or next array at foreach blade laravel

I currently develop a blade View that will loop an array from Controller.

I just create a table that have an aspects, detail aspects, current status, and remark. So, I want loop (with foreach) at my blade view, then at my array there will be a condition that aspects have same value in next row.

For table example:

Aspects     | Detail Aspects | Current Status | Remark
Curriculum  |       1        |      Good      |  Good
Curriculum  |       2        |      Good      |  Good
Curriculum  |       3        |      Good      |  Good
Teaching    |       4        |      Good      |  Good

So for the table, I want to check if prev.Aspect == current.Aspect, so I don't need to print it again, or maybe I can rowspan that .

I already using $index at my foreach, but I only can print it as number, not accessing my Obj[index] value.

Here my blade code :

<table border='1'>
        <tr align='center' class='header'><td>Aspects</td><td>Details</td><td>Current Status</td><td>Remark</td></tr>
        @foreach($prAspect as $index => $data)
            <tr>
                <td>{{$data->praDesc}}</td>
                <td>{{$data->prsDesc}}</td>
                <td>{{$data->currentStatus}}</td>
                <td>{{$data->remark}}</td>
            </tr>
        @endforeach
</table>

Upvotes: 0

Views: 2657

Answers (3)

Timur
Timur

Reputation: 11

Try it might help

@foreach($prAspect as $index => $data)
     <tr>
        <td>{{!$loop->first ? $prAspect[$index- 1]->praDesc : $data->praDesc}}</td>
        <td>{{!$loop->first ? $prAspect[$index - 1]->prsDesc : $data->prsDesc }}</td>
        <td>{{!$loop->first ? $prAspect[$index- 1]->currentStatus : $data->currentStatus }}</td>
        <td>{{!$loop->first ? $prAspect[$index- 1]->remark : $data->remark }}</td>        
   </tr>     
@endforeach

Upvotes: 0

Sandeesh
Sandeesh

Reputation: 11916

Add ->toArray() to your query builder when you fetch the data. This will help your purpose in this case to access the items as an array for easier comparison.

<table border='1'>
    <tr align='center' class='header'><td>Aspects</td><td>Details</td><td>Current Status</td><td>Remark</td></tr>
    @foreach($prAspect as $index => $data)
        <tr>
            <td>{{$data['praDesc']}}</td>
            <td>{{$data['prsDesc']}}</td>
            <td>{{$data['currentStatus']}}</td>
            <td>{{$data['remark']}}</td>
        </tr>
    @endforeach
</table>

Upvotes: 0

zken
zken

Reputation: 1036

You could use for loop instead :

@for ($i = 0; $i < count($prAspect); $i++)
    // use $i as index
    // use $prAspect[$i]
@endfor

Upvotes: 0

Related Questions