1

在 Laravel 中使用@foreach(刀片)时如何排除项目?

示例:
用户有一些文章,在文章详情页面:

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

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

问题:
@foreach,如何排除上面显示的文章?

4

3 回答 3

5

There are a few ways to do this. One option would be a simple if check in the template:

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

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

Another, perhaps better option would be to exclude the main article from the data in the controller:

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);
}
于 2016-08-08T18:23:58.057 回答
0
于 2016-08-08T18:23:47.883 回答
0

使用从第二个元素开始的 for 循环。

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

@if (count($articles) > 1)
<h4>The other articles of this user:&lt;/h4>
@for ($i = 1; $i < count($articles); $i++)
<p>{{$articles[$i]->title}}</p>
@endfor
@endif
于 2016-08-08T18:25:52.717 回答