Home > OS >  How to show image from database with eager loading?
How to show image from database with eager loading?

Time:06-25

I want to display multiple product image from database with eager loading, and when i tried to displaying it, console said localhost:8000/storage/ 404 not found. Any ideas how to solve this? this is my first time using eager loading & relationship on Laravel. Thank you!

Here is my controller :

public function homeProduct(){
  $products = Product::with('productCategory')->get();
  $images = Product::with('productImage')->get();

  return view('home.index', compact('products', 'images'));
}

Product Model :

public function productImage()
{
  return $this->hasMany(ProductImage::class, 'product_id', 'id');
}

Product Image Model :

public function product()
{
  return $this->belongsTo(Product::class, 'id');
}

Here are the index.blade.php View :

@foreach ($products as $p)
    <div >
       <div  data-aos="fade-up">
          <div id="yoreBeans"  data-bs-ride="carousel">
             <div >
                @foreach ($images as $key => $image)
                   <div >
                      <a href="{{ asset('storage/'.$image->path) }}" >
                         <img src="{{ asset('storage/'.$image->path) }}"  alt="">
                      </a>
                    </div>
                @endforeach
              </div>
             </div>
         <div >
             <h3 >{{ $p->name }}</h3>
             <h4 >{{ $p->productCategory->name }}</h4>
         </div>
      </div>
   </div>
@endforeach

CodePudding user response:

Your method $images = Product::with('productImage')->get(); will also return Product objects with images.

What you exactly want is to eager load both realtions and then reference it at the same time:

public function homeProduct(){
    $products = Product::with(['productCategory', 'productImage'])->get();


    return view('home.index', compact('products'));
 }

And your view like this:

@foreach ($products as $p)
    <div >
       <div  data-aos="fade-up">
          <div id="yoreBeans"  data-bs-ride="carousel">
             <div >
                <!--  // this line changed  --->
                @foreach ($p->productImage as $key => $image) 
                   <div >
                      <a href="{{ asset('storage/'.$image->path) }}" >
                         <img src="{{ asset('storage/'.$image->path) }}"  alt="">
                      </a>
                    </div>
                @endforeach
              </div>
             </div>
         <div >
             <h3 >{{ $p->name }}</h3>
             <h4 >{{ $p->productCategory->name }}</h4>
         </div>
      </div>
   </div>
@endforeach
  • Related