Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kosky2005's avatar

Loop using foreach in a collection where contains

I want to get records using foreach in view on collections only where contain 'transcode' or where transCode exist.

this is my collection

Collection {#519 ▼
  #items: array:19 [▼
    754924 => Collection {#500 ▼
      #items: array:4 [▼
        0 => {#441 ▼
          +"Staff_Number": "754924"
          +"opening_bal": "426.44"
        }
        1 => {#465 ▼
          +"Staff_Number": "754924"
          +"total": "390.00"
          +"transCode": "CONTRIBUTION"
        }
        2 => {#478 ▼
          +"Staff_Number": "754924"
          +"total": "136.44"
          +"transCode": "INTEREST"
        }
        3 => {#497 ▼
          +"Staff_Number": "754924"
          +"total": "-100.00"
          +"transCode": "PARTIAL WITHDRAWAL"
        }
      ]
    }
    754928 => Collection {#501 ▼
      #items: array:3 [▼
        0 => {#436 ▼
          +"Staff_Number": "754928"
          +"opening_bal": "311.81"
        }
        1 => {#464 ▼
          +"Staff_Number": "754928"
          +"total": "231.00"
          +"transCode": "CONTRIBUTION"
        }
        2 => {#479 ▼
          +"Staff_Number": "754928"
          +"total": "80.81"
          +"transCode": "INTEREST"
        }
      ]
    }
    754981 => Collection {#502 ▶}
    754989 => Collection {#503 ▶}
    754995 => Collection {#504 ▶}

so i will get something like

CONTRIBUTION: 390.00 INTEREST: 136.44 PARTIAL WITHDRAWAL: -100.00

so something like this

@foreach ($results->where contains as $row)

  {{ $row->transCode }}: {{ $row->total }}

@endforeach 

0 likes
2 replies
biishmar's avatar

@kosky2005

@foreach ($results as $row)

  @if($row->has('transcode'))
    {{ $row->transCode }}: {{ $row->total }}
  @endif

@endforeach 

1 like
kosky2005's avatar

i am getting this error

Call to undefined method stdClass::has() (View:

this is my code in view

    @foreach($getAll as $key => $group)
                {{$key}}

            @foreach($group as  $trans)

               <tr>
                   <td>
                       @if($trans->has('transCode'))
                           {{ $trans->transCode }}: {{ $trans->total }}
                       @endif

                   </td>
               </tr>

            @endforeach

            @endforeach


Please or to participate in this conversation.