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.
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:
- Switching attachments and announcements' position in the array.
- Dumping individual posts. The post appears but even if a post has attachments, they do not show up.
- Changing out $file for another variable name.
- Using Announcement::all()->with('[...
- Many posts have 0 comments or 0 attachments. Prior to me adding in the foreach loop for attachments, posts with 0 comments displayed without issue. Thus, it can't be that just because a post has 0 attachments, it fails.
Also note: the page fails on the FIRST iteration of this loop. If I make it take(1), it still fails, even though the post in question has both comments and announcements.
If I try:
@if(is_array($post->attachments))
@foreach($post->attachments as $attachment)
<div class="">
workin
</div>
@endforeach
@else
<div class="">
not workin
</div>
@endif
It gives a single 'not workin' on the page.
POST MODEL:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Announcement extends Model
{
protected $fillable = array('content', 'author', 'date');
public function comments()
{
return $this->hasMany('App\Comment');
}
public function attachments()
{
return $this->hasMany('App\Attachment');
}
}
ATTACHMENT MODEL:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Attachment extends Model
{
protected $fillable = ['path', 'name', 'announcement_id', 'mime', 'size'];
}
Try add this to your post model..
public function testXY()
{
return $this->hasMany(Attachment::class);
}
Then try..
Route::get('test', function(){
$posts = App\Announcement::with('comments', 'testXY')->get();
foreach($posts as $post){
dd($post->testXY);
}
});
Does it work or is it still the same?
My train of thought is that you might have something that is interfering with the attachments property.. If that is the case, renaming it should solve this problem.
Which then brings up the questions..
- have you added any packages or middlewares?
- have you added any scopes or in any way changed the behavior of the models?
Please or to participate in this conversation.