Home > other >  Invalid argument supplied for foreach() - laravel @foreach
Invalid argument supplied for foreach() - laravel @foreach

Time:06-13

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  data-aos="fade-up" data- aos-duration="1000">
     <div >
         <div id="carouselExampleControls{{ $salle->id }}"  data-bs-ride="carousel">
            <div >
               @foreach ($salle->images as $index => $image)
                   <div  style="height: 200px">
                        <img src="{{ asset('/storage/images/uploads/'.$image) }}"  alt="{{ $image }}" style="object-fit: cover">
                   </div>
               @endforeach

CodePudding user response:

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  data-aos="fade-up" data- aos-duration="1000">
        <div >
            <div id="carouselExampleControls{{ $salle->id }}"  data-bs-ride="carousel">
                <div >
                    @foreach ($salle->images as $index => $image)
                        <div  style="height: 200px">
                            <img src="{{ asset('/storage/images/uploads/'.$image) }}"  alt="{{ $image }}" style="object-fit: cover">
                        </div>
                    @endforeach
  • Related