katie hudson
katie hudson

Reputation: 2893

Laravel 5 - looping over a Collection

can't seem to figure this out. I have the following code

dd($this->project->dsReportingDoc->reportingDocUpload);
if(!empty($this->project->dsReportingDoc->reportingDocUpload)) {
    dd("TEST");
    foreach($this->project->dsReportingDoc->reportingDocUpload as $key){

    }
}

Now the first dd prints out something like the following

Collection {#274 ▼
  #items: array:2 [▼
    0 => ReportingDocUpload {#275 ▶}
    1 => ReportingDocUpload {#276 ▶}
  ]
}

So, there are two items in the Collection. However, the second dd never seems to get executed, so it must never make it into the if statement.

If anything is in the collection, I need to loop them and get a parameter. So I need to see if the item exists first.

Why would my if statement be failing here when it is not empty?

Thanks

Upvotes: 0

Views: 44

Answers (2)

BrynJ
BrynJ

Reputation: 8382

The dd() debug function stops execution of the current request. So you can only call it once and get output - see here.

This is the reason your if condition and foreach aren't executing.

Upvotes: 3

myselfmiqdad
myselfmiqdad

Reputation: 2606

Try this

if($this->project->dsReportingDoc->reportingDocUpload) {
   dd("TEST");
   foreach($this->project->dsReportingDoc->reportingDocUpload as $key){

   }
}

What you can do is, assign the

$this->project->dsReportingDoc->reportingDocUpload

to a variable so you don't have to rewrite it every where.

Upvotes: 0

Related Questions