Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

NKHO's avatar
Level 2

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:

  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('[...
  5. 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'];
}
0 likes
32 replies
NKHO's avatar
Level 2

Haha thank you so much, I was looking deperately for that.

NKHO's avatar
Level 2

It states that 'attachements' is not in the current collection. When I:

dd($posts)

I can see it in there under relational arrays, along with my comments, which works without issue.

NKHO's avatar
Level 2

'attachments'***. I also cannot edit my post.

Snapey's avatar

can you post the dump (expanded) you are missing something obvious which a second eye might catch

NKHO's avatar
Level 2
in b61bb587224d2e70481ac19198cd93ec1ace3dae.php line 27
at CompilerEngine->handleViewException(object(ErrorException), 1) in PhpEngine.php line 44
at PhpEngine->evaluatePath('C:\\wamp64\\www\\phage\\storage\\framework\\views/b61bb587224d2e70481ac19198cd93ec1ace3dae.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'username' => 'NickOstan', 'firstname' => 'Nicholas Kane', 'lastname' => 'Ostan', 'email' => '[email protected]', 'permissions' => '999', 'lab' => 'Moraes', 'posts' => object(Collection), 'orders' => object(Collection), 'meetings' => object(Collection), 'userpoints' => object(Collection))) in CompilerEngine.php line 59
at CompilerEngine->get('C:\\wamp64\\www\\phage\\resources\\views/app.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'username' => 'NickOstan', 'firstname' => 'Nicholas Kane', 'lastname' => 'Ostan', 'email' => '[email protected]', 'permissions' => '999', 'lab' => 'Moraes', 'posts' => object(Collection), 'orders' => object(Collection), 'meetings' => object(Collection), 'userpoints' => object(Collection))) in View.php line 137
at View->getContents() in View.php line 120
at View->renderContents() in View.php line 85
at View->render() in Response.php line 38
at Response->setContent(object(View)) in Response.php line 225
at Response->__construct(object(View)) in Router.php line 602
at Router->prepareResponse(object(Request), object(View)) in Router.php line 560
at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 30
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in SubstituteBindings.php line 41
at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Authenticate.php line 43
at Authenticate->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 65
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Router.php line 561
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 520
at Router->dispatchToRoute(object(Request)) in Router.php line 498
at Router->dispatch(object(Request)) in Kernel.php line 174
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 30
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ValidatePostSize.php line 27
at ValidatePostSize->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Kernel.php line 149
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 54
at require_once('C:\\wamp64\\www\\phage\\public\\index.php') in server.php line 21

There you go. Been stuck on this for over a week now.

Snapey's avatar

no, the dump of the model not the error. you say you dd posts and it looks fine, well, let's see it...

vipin93's avatar

have passed without array like with('comments','attachments')

NKHO's avatar
Level 2

Yes, tried that. No dice.

NKHO's avatar
Level 2

Yes, same thing happens.

NKHO's avatar
Level 2

dd($post->attachments) returns

null
vipin93's avatar

tried using foreach in controller like foreach ($posts as $post){ dd($post->attachments)}

NKHO's avatar
Level 2

Hi, I just tried it. I coded this inline in my web.php:

Route::get('test', function(){
  $posts =       Announcement::with('comments', 'attachments')
                 ->take(15)->orderBy('id', 'desc')
                 ->get();

  foreach($posts as $post){
    dd($post->attachments);
  }
});

When loading /test, it returns again blank page with:

null
NKHO's avatar
Level 2

If I return the $posts object, I can see the attachments:

[{"id":79,"content":"Test announcement!zzzzzzzzzzzzzzzzzzzzz","author":"NickOstan","date":"March 16, 2017, 8:41 pm","attachments":[{"id":53,"announcement_id":79,"name":"QPlAqN9B6X7GVKBR.png","path":"uploads\/NickOstan\/QPlAqN9B6X7GVKBR.png","mime":null,"size":null,"updated_at":"2017-03-16 20:41:33","created_at":"2017-03-16 20:41:33"},{"id":54,"announcement_id":79,"name":"KWC8E0xJNfvxhyxw.jpeg","path":"uploads\/NickOstan\/KWC8E0xJNfvxhyxw.jpeg","mime":null,"size":null,"updated_at":"2017-03-16 20:41:33","created_at":"2017-03-16 20:41:33"},{"id":55,"announcement_id":79,"name":"m1CWy17rQ2bOvY8P.jpeg","path":"uploads\/NickOstan\/m1CWy17rQ2bOvY8P.jpeg","mime":null,"size":null,"updated_at":"2017-03-16 20:41:33","created_at":"2017-03-16 20:41:33"},{"id":56,"announcement_id":79,"name":"LkvnfKWuxp5bNkhl.png","path":"uploads\/NickOstan\/LkvnfKWuxp5bNkhl.png","mime":null,"size":null,"updated_at":"2017-03-16 20:41:33","created_at":"2017-03-16 20:41:33"},{"id":57,"announcement_id":79,"name":"KJMjUU46UZmL4f32.jpeg","path":"uploads\/NickOstan\/KJMjUU46UZmL4f32.jpeg","mime":null,"size":null,"updated_at":"2017-03-16 20:41:33","created_at":"2017-03-16 20:41:33"}],"created_at":"2017-03-16 20:41:33","updated_at":"2017-03-16 20:41:33","comments":[]}
NKHO's avatar
Level 2

comment model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
  protected $fillable = array('content', 'author', 'date', 'announcement_id');
}

attachment model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Attachment extends Model
{
  protected $fillable = ['path', 'name', 'announcement_id', 'mime', 'size'];
}
NKHO's avatar
Level 2

I changed the attachment model to match the array exactly (using array());.

No dice.

vipin93's avatar

hmm looks good did u tried without take()

NKHO's avatar
Level 2

Query:

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

Using loop:

@foreach ($posts as $post)
                @foreach($post->attachments as $file)
                <div>
                  test
                </div>
                @endforeach 
...etc

Same error:

Invalid argument supplied for foreach() (View: C:\wamp64\www\phage\resources\views\app.blade.php
vipin93's avatar

did u misspelled it should be "attachments"

NKHO's avatar
Level 2

Yeah, sorry. Misspelled. Same error.

NKHO's avatar
Level 2

I tried that the other day, no dice :(.

SaeedPrez's avatar
Level 50

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?
NKHO's avatar
Level 2

Hi, I will try this once I get back home tonight.

I have some packages yes, but none that I would expect to affect this. I don't believe I've changed the scopes of any models.

I think your idea is a good approach. I'll make a testXY method, and try it. I may simply have to re-make my attachments model entirely.

One difference I can think of is that I used the command line to make this attachments model whereas teh others I wrote from scratch. I will try all of these once I'm back at my PC.

Next

Please or to participate in this conversation.