Laravel: How can I use Group By within my view?
<p>I am trying to get all students, then group them by graduation year. Within my view, I want to have a headline of the year:</p>

<pre><code>&lt;h2&gt;2016&lt;/h2&gt;
&lt;ul&gt;
    &lt;li&gt;Last, First&lt;/li&gt;
    ...
&lt;/ul&gt;

&lt;h2&gt;2017&lt;/h2&gt;
&lt;ul&gt;
    &lt;li&gt;Last, First&lt;/li&gt;
    ...
&lt;/ul&gt;
</code></pre>

<p>I believe I am close, but not sure of the "Laravel way". The data looks good - as in, the query is getting/grouping correctly, I think my struggle is understanding how to loop through the collection.</p>

<p><strong>MyController.php</strong></p>

<pre><code>public function index()

{
    $students = Student::all()-&gt;groupBy('grad_year');

    return view('student.index', compact('students'));
}
</code></pre>

<p>In my view I can see I am getting this:</p>

<p><strong>MyView.blade.php</strong></p>

<pre><code>{{dd($students)}}

Collection {#178 ▼
    #items: array:2 [▼
        2016 =&gt; Collection {#173 ▼
            #items: array:3 [▼
                0 =&gt; Student {#180 ▶}
                1 =&gt; Student {#181 ▶}
                2 =&gt; Student {#182 ▶}
            ]
        }
        2017 =&gt; Collection {#172 ▶}
    ]
}
</code></pre>

<p><strong>SOLUTION</strong></p>

<p>Here is what my view looks like to get the output I wanted.</p>

<p><strong>MyView.blade.php</strong></p>

<pre><code>@foreach ($collection as $year =&gt; $students)
    &lt;p&gt;{{$year}}&lt;/p&gt;

    &lt;ul class="list-unstyled"&gt;
        @foreach($students as $student)
            &lt;li&gt;&lt;a href=""&gt;{{ $student-&gt;last_name }}, {{ $student-&gt;first_name }}&lt;/a&gt;&lt;/li&gt;
        @endforeach
    &lt;/ul&gt;
@endforeach
</code></pre>