I want to display all the products that have at least one image, then I display one of the image as the card's cover. But the query I made is displaying cards as many as images in the database.
Models
class Product extends Model {
public function getAllData()
{
$data = DB::table('product')
->select('product.*', 'product_images.img')
->join('product_images', 'product_images.product_id', '=', 'product.id')
->paginate(9);
return $data;
}
}
class ProductImage extends Model
{
public function product()
{
return $this->belongsTo(product::class);
}
}
Controller
public function index()
{
$img = ProductImage::find(1);
$data = [
'card' => $img->product->getAllData(),
];
return view('view', $data);
}
View
@foreach ($card as $item)
<div class="card shadow m-3" style="width: 18rem; heigth:24rem">
<div class="inner">
<img class="card-img-top" src="{{$item->img}}" alt="Card image cap">
</div>
<div class="card-body text-center">
<h5 class="card-title">{{$item->name}}</h5>
<p class="card-text">{{$item->description}}</p>
<a href="">Check them out...</a>
</div>
</div>
@endforeach
So I want to retrieve all Product instances with ProductImage instances in single array $card. What is the right way to do this?
Thanks in advance.