Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

djkevino's avatar

Comparing collections

Hey guys,

I'm having trouble to understand how i can achieve the following efficiently in Laravel. Your help will be greatly appreciated.

I have a collection of "Permission"(objects) i want to show the entire list on a page with checkboxes. But whenever the "Permission" is in another collection I want it to check the checkbox.

So for visualisation. I have Collection 1 and 2. If the item consists in both collections i want a checked checkbox. Else i want a not checked checkbox.

Collection 1:

Collection {#546 ▼
  #items: array:5 [▼
    0 => Permission {#529 ▼
      #attributes: array:4 [▼
        "updated_at" => "2018-02-15 06:12:45"
        "created_at" => "2018-02-15 06:12:45"
        "title" => "dashboard"
        "id" => 66
      ]
    }
    1 => Permission {#533 ▶}
    2 => Permission {#537 ▶}
    3 => Permission {#541 ▶}
    4 => Permission {#545 ▶}
  ]
}

Collection 2:

Collection {#593 ▼
  #items: array:3 [▼
    0 => Permission {#584 ▼
      #attributes: array:4 [▼
        "updated_at" => "2018-02-15 06:12:45"
        "created_at" => "2018-02-15 06:12:45"
        "title" => "dashboard"
        "id" => 66
      ]
    }
    1 => Permission {#588 ▶}
    2 => Permission {#592 ▶}
  ]
}

(i deleted the other attributes of the object to not get the post too bloated)

Thanks in advance :)

0 likes
3 replies
Cronix's avatar
Cronix
Best Answer
Level 67

something like this

// Cycle through collection1 and output title
foreach ($collection1 as $main){
    echo $main->title;

    // Check to see if this id exists in collection2
    $exists = $collection2->contains('id', $main->id);

    // If it does, check
    if ($exists) {
        echo ' - check';
    }

    echo '<br>';
}

https://laravel.com/docs/5.6/collections#method-contains

1 like
Joucke's avatar

Have you tried the intersect collection method?

Please or to participate in this conversation.