Laravel diff() method – Laravel Collections

In this tutorial we will learn about Laravel diff() method of Laravel Collections.
The diff
method in Laravel is used to compare two collections and return the items that are present in one collection but not the other. It takes an array or a collection as an argument and returns a new collection containing the items that are present in the original collection but not in the argument.
Here’s an example of how you can use the diff
method:
$collection = collect([1, 2, 3, 4, 5]); $diff = $collection->diff([2, 4, 6, 8]); // $diff will contain [1, 3, 5]
You can also pass a callback as an argument to the diff
method. The callback will be used to compare the items in the collections.
$collection = collect([ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ['id' => 3, 'name' => 'Charlie'], ]); $diff = $collection->diff([ ['id' => 2, 'name' => 'Bob'], ['id' => 4, 'name' => 'David'], ]); // $diff will contain [// ['id' => 1, 'name' => 'Alice'], // ['id' => 3, 'name' => 'Charlie'], // ]
Mention worthy, that the diff
method compares the items by reference, not by value. This means that if two items have the same values but are not the same instance, they will not be considered equal.
If you like this article, please checkout our others article as well.
Laravel:
PHP:
Our YouTube Channel
See you in next one!