You need this to get the last item of a collection $album->images->last()
Apr 15, 2020
4
Level 6
can I get a latest mage trough Laravel relationship?
Can i get the latest image trough relationship?
I have albums. Albums hasHany images and images belongsTo Album i have set this relationship. And it is working as I expected. I would like to foreach loop trough albums and i would like to show the latest uploaded image as thumbnails for these albums. Is it possible to get the latest image in blade?
It is working:
@forelse($albums as $album)
@foreach ($album->images as $image)
{{$image>name}}
@endforeach
@empty
<p class="py-6">There is no album yet!!</p>
@endforelse
But I want only the latest image trough relationship:
@forelse($albums as $album)
{{$album->images->latest()->image->name}}
@empty
<p class="py-6">There is no album yet!!</p>
@endforelse
Level 29
Are there any images in the album ? Maybe you need a check there to ensure that there is at least one image in the album or use the optional helper optional($album->images->last())->name
1 like
Please or to participate in this conversation.