Reference: Fetch first image from foreign key table but this time in Laravel.
I started playing with Laravel and I want to take first image from every post and show these in my blade.
$secondpost = DB::table('posts')
->orderBy('id', 'desc')
->skip(1)
->take(8)
->get();
foreach ($secondpost as $spost)
$secondph = DB::table('post_images')
->select('filename')
->where('post_id', $spost->id)
->limit(1)
->get()
->pluck('filename');
return view ('pages.index', compact('firstp', 'fph', 'secondpost', 'secondph'));
<div class="row">
@foreach ($secondpost as $secondp)
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
<div class="row">
@foreach ($secondph as $sph);
<img src="{{url($sph)}}" class="imgpost" alt="">
@endforeach
<div class="bottomleft">
<p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
<p class="ab-desc">{{$secondp->pret}} Eur</p>
</div>
</div>
</div>
@endforeach
</div>
This code load only one image for every img src. Post_id is foreign key for posts table id.