Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Invalid argument supplied for foreach() – laravel @foreach

I’m trying to display product images in a Bootstrap carousel on index view (each product has many images).
PS: I already did the same thing in a previous project and it worked fine. But in this project, I don’t know why it didn’t work.

  • Here is the index() method that returns all products with their images:

    public function index()
    {
        $salles = Salle::all();
        return view('index', compact('salles'));
    }
    
    
  • Here is the part of the index view that I’m trying to display images on:

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    @forelse ($salles as $salle)
      <div class="col-lg-4 mb-5 mb-lg-0 p-4 text-center box-container" data-aos="fade-up" data- aos-duration="1000">
         <div class="card">
             <div id="carouselExampleControls{{ $salle->id }}" class="carousel slide" data-bs-ride="carousel">
                <div class="carousel-inner">
                   @foreach ($salle->images as $index => $image)
                       <div class="carousel-item {{ $index == 0 ?'active' : '' }}" style="height: 200px">
                            <img src="{{ asset('/storage/images/uploads/'.$image) }}" class="d-block w-100" alt="{{ $image }}" style="object-fit: cover">
                       </div>
                   @endforeach
    

>Solution :

It is possible same sales still does not have image. So use this code

@forelse ($salles as $salle)
@if(empty($salle->images))
    @continue
@endif
<div class="col-lg-4 mb-5 mb-lg-0 p-4 text-center box-container" data-aos="fade-up" data- aos-duration="1000">
    <div class="card">
        <div id="carouselExampleControls{{ $salle->id }}" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-inner">
                @foreach ($salle->images as $index => $image)
                    <div class="carousel-item {{ $index == 0 ?'active' : '' }}" style="height: 200px">
                        <img src="{{ asset('/storage/images/uploads/'.$image) }}" class="d-block w-100" alt="{{ $image }}" style="object-fit: cover">
                    </div>
                @endforeach
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading