HDTuto.com

How to Remove Duplicate Items from Collection in Laravel?



Hi Artisan,

Here, i will show you how to works remove duplicates from collection laravel. i explained simply about how to remove duplicate rows in laravel. you can see laravel collection->unique by key. Here you will learn laravel eloquent remove duplicates.

In this example i will explain you how to use laravel collection uniuqe and i will give you some example that will help you to delete duplicates records from collection in laravel.

Let's see bellow one by one example with output:

Example 1:

public function index()

{

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

$uniqueCollection = $myCollection->unique();

$uniqueCollection->all();

dd($uniqueCollection);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => 1

[1] => 2

[3] => 3

[4] => 4

[6] => 5

[7] => 6

)

)

Example 2:

public function index()

{

$myCollection = collect([

['id'=>1, 'name'=>'Hardik', 'state'=>'Gujarat', 'country'=>'India'],

['id'=>2, 'name'=>'Paresh', 'state'=>'Gujarat', 'country'=>'India'],

['id'=>3, 'name'=>'Vimal', 'state'=>'MP', 'country'=>'India'],

['id'=>4, 'name'=>'John', 'state'=>'New York', 'country'=>'US'],

['id'=>5, 'name'=>'Ken', 'state'=>'New York', 'country'=>'US'],

]);

$uniqueCollection = $myCollection->unique('country');

$uniqueCollection->all();

dd($uniqueCollection);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

[state] => Gujarat

[country] => India

)

[3] => Array

(

[id] => 4

[name] => John

[state] => New York

[country] => US

)

)

)

Example 3:

public function index()

{

$myCollection = collect([

['id'=>1, 'name'=>'Hardik', 'state'=>'Gujarat', 'country'=>'India'],

['id'=>2, 'name'=>'Paresh', 'state'=>'Gujarat', 'country'=>'India'],

['id'=>3, 'name'=>'Vimal', 'state'=>'MP', 'country'=>'India'],

['id'=>4, 'name'=>'John', 'state'=>'New York', 'country'=>'US'],

['id'=>5, 'name'=>'Ken', 'state'=>'New York', 'country'=>'US'],

]);

$uniqueCollection = $myCollection->unique(function ($item) {

return $item['country'].$item['state'];

});

$uniqueCollection->all();

dd($uniqueCollection);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

[state] => Gujarat

[country] => India

)

[2] => Array

(

[id] => 3

[name] => Vimal

[state] => MP

[country] => India

)

[3] => Array

(

[id] => 4

[name] => John

[state] => New York

[country] => US

)

)

)

I hope it can help you...




April 26, 2020 | Category : Laravel



Blog Search


Copyright © 2020 HDTuto.com. All rights reserved.