Laravel Collection移除tag_name字段并提取去重标签的方法
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:
- Extract all
tag_namevalues into a separate, unique Collection - Remove the
tag_namefield from every element in the main Collection - 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 thetag_namefield on your items.slice()is for extracting a subset of the Collection by position, not modifying element properties.
Final Result
$tagswill be a Collection containing["RPG", "Turn based", "Simulation"](unique, ordered)$mainCollectionwill have a single entry for each game, with all fields excepttag_nameintact.
内容的提问来源于stack exchange,提问作者M.Pau

