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. Thanks for any help.



via Vranvs

Advertisement