php - How to exclude an item when using @foreach in Laravel? -


how exclude item when using @foreach (blade) in laravel?

example:
user has articles, in article detail page:

<p>article detail:</p> <h2>{{$article->title}}</h2> <p>{{$article->content}}</p>  <h4>the other articles of user:</h4> @foreach ($articles $article) <p>{{$article->title}}</p> @endforeach 

question:
in @foreach, how exclude article has been shown above?

there few ways this. 1 option simple if check in template:

<p>article detail:</p> <h2>{{$article->title}}</h2> <p>{{$article->content}}</p>  <h4>the other articles of user:</h4> @foreach ($articles $otherarticle)     @if($article->id !== $otherarticle->id)         <p>{{$article->title}}</p>     @endif @endforeach 

another, perhaps better option exclude main article data in 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); } 

Comments