提问者:小点点

是否可以检查所有foreach循环结果的条件是否为真?


如果foreach循环中给出的if条件对于foreach循环的所有迭代都是true,我想返回一个错误消息。意味着,只有在所有foreach循环迭代(不仅仅是特定迭代)中$id存在于CoursePublishChaptercontent中,我才需要中断。我该怎么做?

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);
                    }
                  }

共1个答案

匿名用户

您可以使用每个收集方法:

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

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