Home > database >  Possible to check if condition true on all foreach loop result?
Possible to check if condition true on all foreach loop result?

Time:12-22

I wanted to return an error msg if the if condition given inside the foreach loop is true for all the iterations of foreach loop. Means,only if $id exists in CoursePublishChaptercontent in all the foreach loop iterations (not just only in a particular iteration),i need to break . How can i do that?

foreach($chapterContentId as $id){
                    if(CoursePublishChaptercontent::where('course_chapter_content_id',$id)->exists()){
                        return response()->json([
                            'message' => "Course publish failed",
                            'statusCode' => 400,
                            'status' => 'Failed',
                            'errorMessages' =>  ['Availble course chapters and contents are already published']
                        ], 400);
                    }
                  }

CodePudding user response:

You can use the every collection method:

$val = collect($chapterContentId)->every(function($id) {
  return CoursePublishChaptercontent::where('course_chapter_content_id',$id)->exists();
}):

if ($val) {
  // all exist
} else {
  // all don't exist
}

CodePudding user response:

Alternatively, you could also not do a loop at all and bring this down to 1 single query instead of doing X number of queries because of the iterations:

// make sure there are only unique values in the list
// if array
$chapterContentIds = array_unique($chapterContentIds);
// if collection
$chapterContentIds = $chapterContentIds->unique();

$allExist = CoursePublishChaptercontent::whereIn('course_chapter_content_id', $chapterContentIds)
    ->count() == count($chapterContentIds);
  • Related