Invalid argument supplied for foreach() – laravel @foreach

Issue

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

Answered By – Davit Zeynalyan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published