【问题标题】:Laravel 5.2: Can variable be classified in view?Laravel 5.2:变量可以在视图中分类吗?
【发布时间】:2016-08-20 17:01:40
【问题描述】:

我正在使用 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"),未发表的文章显示在另一张卡片中。
它们可以在视图中分类吗?因此,它不需要查询两次。

【问题讨论】:

  • 为什么不在foreach 循环中测试status?类似@if ($article-&gt;status === 1) { 'published card' } @else { 'unpublished card' } @endif。
  • 你能解释一下你对卡片的意思吗?

标签: php laravel


【解决方案1】:

尝试使用收集方法where()

@foreach ($articles->where('published', 1)->all() as $article)

只需将published 和1 更改为真实的即可。

【讨论】:

  • 我很确定这行不通。我认为-&gt;all() 应该是-&gt;get()
  • @Slence,这个例子来自官方文档(点击我答案中的链接)。
  • all 方法只返回集合所代表的底层数组 - laravel.com/docs/5.1/collections#method-all
  • @AlexeyMezenin 用于收藏。使用 QueryBuilder/Eloquent,它是 get()。 all() 用于返回数据库每一行的查询。
  • @aynber,刚刚在 TInker 中检查了这个,all() 工作并返回一个数组。
猜你喜欢
  • 1970-01-01
  • 2018-06-10
  • 2017-05-12
  • 1970-01-01
  • 2012-07-12
  • 2011-08-31
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多