Skip to content
Advertisement

Laravel Nested Foreach loop from collection

I have the following collection:

Screenshot: enter image description here What I would like to do is return each state college across in 3 rows by state using a blade template. For example:

Massachusetts

college 1 college 2 college 3

Florida

college 1 college 2 college 3

college 4

I have tried many different suggested examples from other posts, but have not been able to find a solution.

Here is what I have tried:

Here is what I have tried:

     @foreach ($colleges as $college)
      @foreach($college as $state)
        <h1 style="center">{{ $state[0]['College']['state'] }}</h1>
      <ul class="nospace clear">
        <li class="one_quarter first">
          <a href="#">
            <img src="{{ asset('storage/' . $state[0]['College']['logo'])  }}" alt="{{ $state[0]['College']['college'] }}" />
          </a>
          <h3 class="center">{{ $state[0]['College']['college'] }}</h3>
        </li>
      </ul>
      @endforeach
@endforeach

Any help would be greatly appreciated.

Greg

Advertisement

Answer

From the looks of your collection screenshot, it has the following structure:

[
  state
    college
    college

  state
    college
    college
    college

  ...
]

Therefore, if you foreach over the $states collection, taking the $key as the state name and the $value as that state’s college collection, you can do the following:

@foreach ($states as $state => $colleges)
    <h1 style="center">{{ $state }}</h1>

    <ul class="nospace clear">
        @foreach ($colleges as $college)
            <li class="one_quarter first">
                <a href="#">
                    <img src="{{ asset('storage/' . $college->logo) }}" alt="{{ $college->college }}" />
                </a>
                <h3 class="center">{{ $college->college }}</h3>
            </li>
        @endforeach
    </ul>
@endforeach
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement