php – How to fix reduce Method returning nothing (Laravel)-ThrowExceptions

Exception or error:

I want to iterate through $student collection and multiply each value from $defaultValue and check whether it’s less than or equal to the number I am getting from json data $jsonData->value. if any is less than $jsonData->value, will return true. But it is not returning anything ! why is that ? i have checked the code and found that, when i print $carry its not assigned as false. (according to this the default value of $carry is false). how to fix it ?

$jsonData = json_decode($request->data);

if ($jsonData->value!==0){
   foreach ($array as $key => $data){
      $lectures = Lecture::where('hall_id','=',$data['id'])->get();
           foreach ($lectures as $lecture){
              $student = Student::where('lecture_id','=',$lecture->id)
                   ->where('date','>=',$jsonData->dateOne)
                   ->where('date','<=',$jsonData->dateTwo)
                   ->get();

              $defaultValue = $lecture->value;

              if (!$student ->isEmpty()){

                   $multiplied = collect($student )
                      ->reduce(function($carry, $item) use ($defaultValue ,$jsonData){
                           return $carry || $item->number * $defaultValue <=$jsonData->value;
                   }, false);

          }

    }
}

$student returns

[{"id":2,"number ":10},{"id":79,"number ":1},{"id":9,"number ":4}] 

$defaultValue reurns

2

$jsonData->value returns

10
How to solve:

Try this

$carry || (($item->number * $defaultValue) <=$jsonData->value);

Leave a Reply

Your email address will not be published. Required fields are marked *