2016-04-26 51 views
1

我正在使用Laravel 5.2。
我的问题是:
可以将变量分类吗?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 =“卡”)中显示的发表文章,而在另一张卡中显示的未发表的文章。
它们可以分类吗?因此,它不需要查询两次。

+0

为什么不只是测试'foreach'循环内的'status'?就像'@if($ article-> status === 1){'published card'} @else {'unpublished card'} @ endif'。 – camelCase

+0

你能解释一下你的卡片是什么意思吗? –

回答

1

尝试使用收集方法where()

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

只要改变published1以假乱真。

+0

我很确定这不会起作用。我认为' - > all()'应该是' - > get()' –

+0

@Slence,这个例子来自官方文档(点击我的答案中的链接)。 –

+0

*全部方法只返回集合表示的底层数组* - https://laravel.com/docs/5.1/collections#method-all –