Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How can I use Group By within my view?

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:

<h2>2016</h2>
<ul>
    <li>Last, First</li>
    ...
</ul>

<h2>2017</h2>
<ul>
    <li>Last, First</li>
    ...
</ul>

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.

MyController.php

public function index()

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

    return view('student.index', compact('students'));
}

In my view I can see I am getting this:

MyView.blade.php

{{dd($students)}}

Collection {#178 ▼
    #items: array:2 [▼
        2016 => Collection {#173 ▼
            #items: array:3 [▼
                0 => Student {#180 ▶}
                1 => Student {#181 ▶}
                2 => Student {#182 ▶}
            ]
        }
        2017 => Collection {#172 ▶}
    ]
}

SOLUTION

Here is what my view looks like to get the output I wanted.

MyView.blade.php

@foreach ($collection as $year => $students)
    <p>{{$year}}</p>

    <ul class="list-unstyled">
        @foreach($students as $student)
            <li><a href="">{{ $student->last_name }}, {{ $student->first_name }}</a></li>
        @endforeach
    </ul>
@endforeach
like image 532
Damon Avatar asked Mar 12 '23 21:03

Damon


1 Answers

something like:

$studentsByYear = $students;

foreach ($studentsByYear as $year => $students) {
 echo "<h2>$year</h2>";
 echo "<ul>";
   foreach ($students as $student) {
     echo "<li>".$student->name."</li>";
   }
 echo "</ul>";
}
like image 173
Amir Bar Avatar answered Mar 29 '23 04:03

Amir Bar