Kamran G.
Kamran G.

Reputation: 463

Laravel @foreach

I need to get each comment of news . Its working good for firstorFail() item

{{$news->comments()->firstOrFail()->name}}

But bring me empty result when im try this one with foreach:

 @foreach($news->comments() as $comment)
      {{$comment->name}}
      @endforeach

Upvotes: 1

Views: 157

Answers (2)

Filip Koblański
Filip Koblański

Reputation: 9988

This: $news->comments() bringing you query builder probably. So what you need is to ->get() for execute query like this:

@foreach($news->comments()->get() as $comment)
    {{$comment->name}}
@endforeach

Edit

or as a @Roy Philips mentioned: $news->comments

Upvotes: 0

Frnak
Frnak

Reputation: 6792

The function firstOrFail will return exactly one comment. Seems like you actually want all comments? You should use this in your controller

$news->comments; // yeah that's it, it will load all comments

Also return news

return view('my.view', compact('news'));

Then use it in blade

 @foreach($news->comments as $comment)
   {{$comment->name}}
 @endforeach

the line

$news->comments() 

would require you to also call ->get() , because comments() will return the relation instead of the actual data.

Upvotes: 1

Related Questions