Wednesday, March 15, 2017

Laravel: Invalid argument supplied for foreach()

I'm trying to iterate through two relational arrays attached to my ANNOUNCEMENT object (Announcement hasMany comments, hasMany attachments).

This is my code which grabs the stuff from the database:

$posts = Announcement::with(['comments', 'attachments'])
          ->take(30)->orderBy('id', 'desc')
          ->get();

It is working perfectly fine for the comments array, but when I try to set up for my attachments, it fails:

@foreach ($posts as $post)    
  @foreach ($post->comments as $comment)
    //this works perfectly fine.                         
  @endforeach

  @foreach ($post->attachments as $file)
   // this gives me the error as below.
  @endforeach
@endforeach

I get:

Invalid argument supplied for foreach()

I used dd($posts) to check if my attachments array was in fact there, and it is:

enter image description here

I know there are other posts with this question, but none of them relate to mine. Not sure what's going on here.

What I have tried:

  1. Switching attachments and announcements' position in the array.
  2. Dumping individual posts. The post appears but even if a post has attachments, they do not show up.
  3. Changing out $file for another variable name.
  4. Using Announcement::all()->with('[...


via Vranvs

Advertisement