Kamran G. Kamran G. - 6 months ago 22
PHP Question

Laravel @foreach

I need to get each comments 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

Answer

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

Comments