Arief G
Arief G

Reputation: 43

Laravel 8 eloquent querying with relations

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.

Upvotes: 1

Views: 107

Answers (1)

Hari Darshan
Hari Darshan

Reputation: 1920

What I understand from you're requirement is you want to display all the products which have atleast 1 image against a product.

public function index()
{
    $products = Product::has('image')
       ->with('image')
       ->get();
    $data = [
        'card' => $products,
    ];
    return view('view', $data);
}

This will return all the products which has 1 image and the image can be used via image relation

@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->image->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

Product Model

class Product extends Model 
{
    public function image()
    {
        return $this->hasOne(ProductImage:class);
    }
   
    public function images()
    {
        return $this->hasMany(ProductImage:class);
    }
}

I have only used Laravel Eloquent, so the way I've shown the rendering of the products in view might be wrong

Upvotes: 2

Related Questions