2016-08-08 43 views
1

如何在Laravel中使用@foreach(blade)時排除項目?如何在Laravel中使用@foreach時排除項目?

例如:
用戶有一些文章,在文章詳細頁面:

<p>Article detail:</p> 
<h2>{{$article->title}}</h2> 
<p>{{$article->content}}</p> 

<h4>The other articles of this user:</h4> 
@foreach ($articles as $article) 
<p>{{$article->title}}</p> 
@endforeach 

問:
@foreach,如何排除已被上面顯示的文章?

+1

工匠在控制器或模型中處理數據,視圖僅用於顯示數據。 – Kyslik

回答

0

如果你不想顯示article在詳細信息頁面中The other articles of this user:

在控制器,你應該這個細節頁面上發送id of article查看

而在視圖

<p>Article detail:</p> 
<h2>{{$article->title}}</h2> 
<p>{{$article->content}}</p> 

<h4>The other articles of this user:</h4> 
@foreach ($articles as $article) 
    @if($article->id !== $article_id) 
     <p>{{$article->title}}</p> 
    @endif 
@endforeach 

article_idvariable您從controller發送

4

有幾種方法可以做到這一點。 一種選擇是簡單的,如果檢查模板:

<p>Article detail:</p> 
<h2>{{$article->title}}</h2> 
<p>{{$article->content}}</p> 

<h4>The other articles of this user:</h4> 
@foreach ($articles as $otherArticle) 
    @if($article->id !== $otherArticle->id) 
     <p>{{$article->title}}</p> 
    @endif 
@endforeach 

另一個,也許更好的選擇是排除來自數據控制器的主要文章:

function showArticle(Article $article) 
{ 
    $otherArticles = $article->user->articles->filter(
     function($otherArticle) use($article) { 
      return $otherArticle->id !== $article->id; 
     }); 
    return view('someview') 
     ->with('article', $article) 
     ->with('otherArticles', $otherArticles); 
} 
0

使用for循環從第二個元素開始。

<p>Article detail:</p> 
<h2>{{$article->title}}</h2> 
<p>{{$article->content}}</p> 

@if (count($articles) > 1) 
<h4>The other articles of this user:</h4> 
@for ($i = 1; $i < count($articles); $i++) 
<p>{{$articles[$i]->title}}</p> 
@endfor 
@endif 
相關問題