phplaravelforeachdumpdd

Script execution / foreach() loop stops when I call Laravel's dd() function


When I call dd() (die and dump) like dd($user->friends()); I only get the output from the first record in the collection.

When I try to do something like:

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

This is what I get :

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
}

But when I dump out the collection without looping, I can see multiple records.

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
    }
  ]
}

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?


Solution

  • 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) {
        dump($friend);
    }