Y
Y
Yuri Kulaxyz2019-08-22 12:06:50
Laravel
Yuri Kulaxyz, 2019-08-22 12:06:50

How to display posts in blade if some have a picture and some don't?

The task is this: There are posts and if the post has pictures, then you need to display the first one, and if not, then the block remains empty. That's what I'm doing:

@if(!is_null($post->images))
         <img class="card-img-top" src="{{ asset('storage/images/posts') . '/' . $post->images()->first()->path ?? null}"style="width: 200px" alt="">
@endif

I get the error "Trying to get property of non-object". I understand that it appears due to the fact that some posts do not have an image, and the @if condition only affects whether the html is visible or not. But how then to get rid of the error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2019-08-22
@Kulaxyz

the @if condition only affects whether the html is visible or not.
You're not right.
Pictures are a collection, it will never be null, so your check always passes. It should be like this:
$post->images()->first()->path
And here you are making an extra request to the database. It should be like this:$post->images->first()->path

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question