You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Collection移除tag_name字段并提取去重标签的方法

Laravel Collection: Extract Unique Tags & Clean Up Main Collection

Problem

I have a Laravel Collection with 54 elements where the same game appears multiple times (once per tag). For example:

Collection {#430 ▼
  #items: array:3 [▼
    0 => {#435 ▼
      +"name": "Persona 5"
      +"cover": "cover_persona-5_playstation-3.png"
      +"bio": "This is a syno"
      +"all_nb_rank": null
      +"platform_name": "Sony Playstation 3"
      +"tag_name": "RPG"
      +"developper": "Deep Silver"
      +"publisher": "Atlus"
    }
    // ... other duplicate entries with different tag_name values
  ]
}

I want to:

  1. Extract all tag_name values into a separate, unique Collection
  2. Remove the tag_name field from every element in the main Collection
  3. Remove duplicate entries from the main Collection (so only one entry per game remains)

I already know how to get the tags with $tags = $collection->pluck('tag_name'), but I can't figure out how to remove the tag_name field from the main Collection using Laravel's built-in methods (tried forget() and slice() with no luck, and I don't want to convert to a plain array to use unset()).

Solution

Here's a clean, Laravel-native way to handle both tasks without converting to plain arrays:

1. Extract & Deduplicate Tags

Your initial pluck() call works perfectly—just chain unique() to remove duplicate tags, and values() to reset the Collection's keys to sequential numbers (optional but makes the tag collection cleaner):

$tags = $collection->pluck('tag_name')->unique()->values();

2. Clean Up & Deduplicate Main Collection

To remove the tag_name field from every element, use map->except('tag_name') (Laravel's concise arrow function syntax for Collections). Then chain unique() to filter out duplicate game entries: since we've removed the varying tag_name field, all duplicate game entries will now match exactly, so unique() will automatically keep only one copy per game:

$mainCollection = $collection->map->except('tag_name')->unique();

Why Your Previous Attempts Failed

  • forget('tag_name') targets top-level keys in the Collection (like the numeric indexes 0, 1, 2), not properties inside each element. That's why it didn't affect the tag_name field on your items.
  • slice() is for extracting a subset of the Collection by position, not modifying element properties.

Final Result

  • $tags will be a Collection containing ["RPG", "Turn based", "Simulation"] (unique, ordered)
  • $mainCollection will have a single entry for each game, with all fields except tag_name intact.

内容的提问来源于stack exchange,提问作者M.Pau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:53:10