2016-04-26 78 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 –