Laravel 5 Collections: Determine Which Collection Elements are Not Present in the Provided Collections With diff

April 22, 2018 —John Koster

The diff method is used to determine which items in the collection are not present in the supplied $items collection. $items can be be either an array, or another instance of Collection. The diff method returns a new instance of Collection.

#Signature

1public function diff(
2 $items
3);

#Example Use

The following examples will demonstrate the usage of the diff:

1use Illuminate\Support\Collection;
2 
3// Create the first collection instance.
4$firstCollection = new Collection([
5 'first', 'second', 'third'
6]);
7 
8// Create the second collection instance.
9$secondCollection = new Collection([
10 'third', 'fourth', 'fifth'
11]);
12 
13// ['first', 'second']
14$firstCollection->diff(['third', 'fourth', 'fifth']);
15 
16// ['first', 'second']
17$firstCollection->diff($secondCollection);
18 
19// ['fourth', 'fifth']
20$secondCollection->diff($firstCollection);

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.