我正在使用Laravel 5.2。
我的问题是:
变量可以在视图中分类吗?
例如:
有一个控制器,它可以获取当前用户的所有文章,像这样:
public function index()
{
$user='Auth::user();
$articles = $user->articles;
return view('user.dashboard.index', compact('articles'));
}
鉴于此,下面的这些代码可以显示文章,如下所示:
<div class="card">
<div class="card-header">
Articles
</div>
@if ($articles!=null)
<table class="table table-sm">
<thead>
<tr>
<th>title</th>
<th>created time</th>
<th>status</th>
</tr>
</thead>
<tbody>
@foreach ($articles as $article)
<tr>
<td>{{$article->title}}</td>
<td>{{$article->created_at}}</td>
<td>{{$article->status}}</td>
</tr>
@endforeach
</tbody>
</table>
@else
<p>Nothing</p>
@endif
</div>
这些文章可分为两种类型:
1、"已发布",状态1
。
2、"未发表",状态0
。
问题:
我希望已发表的文章显示在卡片中(div class="card"),而未发表的文章显示在另一张卡片中。
它们是否可以在视图中分类?因此,它不需要查询两次。
尝试使用 收集方法 where()
@foreach ($articles->where('published', 1)->all() as $article)
只需将published
和1
更改为真实的即可。