Nathan Siafa
Nathan Siafa

Reputation: 741

Looping through associative array returning single results when the are more to be returned in Laravel

I have this query that returns an associative array. What I have realize is that when I try to have an if statement that checks if one date equals another I only get the condition to run against the first value only which is 2017-09-21.

Here is the query:

$startDates = Academic::all()->pluck('date_start');

Query results:

Collection {#299
  #items: array:2 [
    0 => Carbon {#298
      +"date": "2017-09-21 00:00:00.000000"
      +"timezone_type": 3
      +"timezone": "UTC"
    }
    1 => Carbon {#304
      +"date": "2018-06-07 00:00:00.000000"
      +"timezone_type": 3
      +"timezone": "UTC"
    }
  ]
}

My loop and if statements:

$recieveDate = Carbon::createFromDate($date); // assume value is 2017
foreach ($startDates as $key => $value) {

    // this only check against 2017 and not 2018
    if ($value->year == $recieveDate->year) {
        return response()->json(['exists' => 'The year of School Date Start already exists']);
    } else {
        return response()->json(['none' => null]);
    }
}

How do I get it to check if $recieveDate equals the second value in the collection array which is 2018-06-07?

Upvotes: 0

Views: 33

Answers (1)

cre8
cre8

Reputation: 13562

You loop over all entries and if you get a match you change the value to true.

$recieveDate = Carbon::createFromDate($date); // assume value is 2017
$found = false;
foreach ($startDates as $key => $value) {
    if ($value->year == $recieveDate->year) {
       $found = true;
       break; //stop loop so you don't have to iterate more.
    }
}
if($found) {
     return response()->json(['exists' => 'The year of School Date Start already exists']);
} else {
    return response()->json(['none' => null]);
}

Since $startDates is a collection you can use one of it's methods to find an element:

$recieveDate = Carbon::createFromDate($date);
$found = $collection->search(function ($item, $key) use ($recieveDate) {
    return $item->year == $recieveDate->year;
});

if($found) {
     return response()->json(['exists' => 'The year of School Date Start already exists']);
} else {
    return response()->json(['none' => null]);
}

Upvotes: 2

Related Questions