laraveleloquentlaravel-collection

Modify single Item of Laravel Collection without mapping every single item


I loop trough an eloquent Collection and I want to add the data to another Collection called "$tagCollection". If an entry with the same tag_id already exists I only want to increase the rating-column for the existing entry. At the moment it looks like this. Has anyone an Idea?

$tagCollection = collect();

$entries->each(function($entry) use($tagCollection){
   $tagId = $entry->tag_id;

   //something like this
   if($tagCollection->contains('tag_id', $tagId)){
      $tagCollection->update ('rating' => $oldRating + 0.5)
    } else{
        $tagCollection->push(array(
            'tag_id' => $tagId,
            'rating' => 0.35
        ));
    }

 });

I also tried to use ->pull() to remove the Item out of the Collection and then push it again with the new rating but I also do not know how


Solution

  • Can you do it with array instead of collection? For example:

    $tagArray = [];
    $entries->each(function ($entry) use (&$tagArray) {
        if (isset($tagArray[$entry['tag_id']])) {
            $tagArray[$entry['tag_id']] += 0.5;
        } else {
            $tagArray[$entry['tag_id']] = 0.35;
        }
    });