0👍
Not every $post
has a like, so you are basically trying to access a property of null
which is, obviously, not an object. Your way around this is simple and I think you are overlooking it because you are expecting Laravel to just handle that error for you.
@foreach( $posts as $post )
<p>{{ $post->name }}</p>
<p>{{ $post->likes ? $post->likes->id : 'No Likes' }}</p>
@endforeach
Also, keep in mind here you have called it likes
, which leads me believe it a one to many relationship (a post can have MANY likes). In that case, you are going to need to loop over $posts->likes
to get the ID for each one:
@foreach($posts as $post )
<p>{{ $post->name }}</p>
<p>
@if( $post->likes)
@foreach( $post->likes as $like )
{{ $like->id }} @if (!$loop->last), @endif
@endforeach
@else
'No Likes';
@endif
</p>
@endforeach
Source:stackexchange.com