How to Remove Duplicates from Collection in Laravel 12

In this tutorial, I’ll show you how to remove duplicate values from a Laravel 12 collection using the unique() method. Whether you’re working with simple arrays, Eloquent model collections, or nested data, this guide will help you clean up duplicates easily.

How to Remove Duplicates from Collection in Laravel 12

Laravel collections offer a unique() method that filters out duplicate values from the collection. You can specify a key or pass a callback to customize the behavior.

How to Remove Duplicates from Collection in Laravel 12

 

Example 1: Remove Duplicates from Simple Collection

$collection = collect([1, 2, 2, 3, 4, 4, 5]);

$unique = $collection->unique();

dd($unique->values());
// Output: [1, 2, 3, 4, 5]

 

Example 2: Remove Duplicates by Key in Associative Array

$collection = collect([
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 1, 'name' => 'John'],
]);

$unique = $collection->unique('id');

dd($unique->values());
// Output: Only unique `id`s are retained

 

Example 3: Remove Duplicates with Callback

$collection = collect([
    ['name' => 'John'],
    ['name' => 'john'],
    ['name' => 'Jane'],
]);

$unique = $collection->unique(function ($item) {
    return strtolower($item['name']);
});

dd($unique->values());

 

Example 4: Remove Duplicates from Eloquent Collection

$users = User::all();

$uniqueUsers = $users->unique('email');

dd($uniqueUsers->values());

 

Example 5: Remove Duplicates by Nested Key

$collection = collect([
    ['user' => ['id' => 1, 'name' => 'Alice']],
    ['user' => ['id' => 2, 'name' => 'Bob']],
    ['user' => ['id' => 1, 'name' => 'Alice']],
]);

$unique = $collection->unique('user.id');

dd($unique->values());

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS