Array of objects , that won't loop in a foreach in laravel

- 1 answer

Ad

I'm not sure this is really a laravel question but, when I dd(die and dump) this dd($user->friends()); I get the following. I did notice that it is a collection. I'm not sure if that means something different or not. But it still should be an array of items I believe. With the first user at the [0] mark and next [1], etc...

Collection {#184 ▼
  #items: array:2 [▼
    0 => User {#189 ▼
      #table: "users"
      #fillable: array:7 [▶]
      #hidden: array:3 [▶]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:11 [▶]
      #original: array:13 [▶]
      #relations: array:1 [▶]
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    1 => User {#190 ▼
      #table: "users"
      #fillable: array:7 [▶]
      #hidden: array:3 [▶]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:11 [▶]
      #original: array:13 [▶]
      #relations: array:1 [▶]
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
  ]
}

So then when I try to do something like :

foreach($user->friends() as $friend) {
dd($friend);
}

This is what I get after doing that:

User {#189 ▼
  #table: "users"
  #fillable: array:7 [▶]
  #hidden: array:3 [▶]
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:11 [▶]
  #original: array:13 [▶]
  #relations: array:1 [▶]
  #visible: []
  #appends: []
  #guarded: array:1 [▶]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

I want it to loop through all the users not just the first one. Is there a reason it is doing this. Am I doing the foreach wrong or does it have something to do with the collection?

Ad

Answer

Ad

When you do your foreach, you're only seeing one entry because of the dd(). Remember, it is "dump and die", so on the very first iteration, you're dumping the record and then dying.

Try this out:

foreach($user->friends() as $friend) {
    print_r($friend);
}
Ad
source: stackoverflow.com
Ad