Dam*_*mon 3 laravel-5.2 laravel-blade
我正在努力吸引所有学生,然后按毕业年份将其分组。在我看来,我想成为本年度的标题:
<h2>2016</h2>
<ul>
<li>Last, First</li>
...
</ul>
<h2>2017</h2>
<ul>
<li>Last, First</li>
...
</ul>
Run Code Online (Sandbox Code Playgroud)
我相信我已经接近,但不确定“ Laravel方式”。数据看起来不错-例如,查询正在正确获取/分组,我认为我的工作是理解如何遍历集合。
MyController.php
public function index()
{
$students = Student::all()->groupBy('grad_year');
return view('student.index', compact('students'));
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我可以看到这一点:
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 ?}
]
}
Run Code Online (Sandbox Code Playgroud)
解
这是我的视图想要获得所需输出的样子。
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
Run Code Online (Sandbox Code Playgroud)
就像是:
$studentsByYear = $students;
foreach ($studentsByYear as $year => $students) {
echo "<h2>$year</h2>";
echo "<ul>";
foreach ($students as $student) {
echo "<li>".$student->name."</li>";
}
echo "</ul>";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5895 次 |
| 最近记录: |