skip to Main Content

Can I simplify this code without foreach?

$userQuestIds = [2,4,45,586,16,2,143,234,654,78,56];

$typeQuests = [];
foreach ($userQuestIds as $qId) {
    $typeQuests[] = Quest::where(['id' => $qId])->first();
}

3

Answers


  1. You can use whereIn:

    $typeQuests = Quest::whereIn('id', $userQuestIds)->get();
    

    NOTE: this approach is better for columns other than id (as primary). I think @andriy-Lozynskiy solution is the best way.

    Login or Signup to reply.
  2. If id is a primary key the shortest way is:

    $typeQuests = Quest::find($userQuestIds);
    
    Login or Signup to reply.
  3. You can use the whereIn() method on the QueryBuilder class

    $userQuestIds = [2,4,45,586,16,2,143,234,654,78,56];
    $typeQuests = Quest::whereIn('id', $userQuestIds)->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search