In this article explain how to works Laravel collection get unique values. This tutorial will give you simple example of how to get unique values from array in Laravel. I explained easy about laravel collection by column.
In Laravel, you can retrieve unique values from a collection using the unique() method. This is useful when have a collection of data and want filter remove duplicate values.
What is the unique() method?
The unique() method in Laravel collections helps you to remove duplicate values from a collection. If you are working with objects, you can specify the key on which you want to check uniqueness.
- Unique on Primitive values: When your collection contains simple values like integer, strings etc. When you can directly call unique() method without specifying any key.
- Unique on specific keys: When you are working with array and objects, you can pass the key you want to check for uniqueness.
I will give you simple and multiple example how to get unique value from laravel collection object.
Let’see below example.
Example 1: Laravel collection get unique values
1. Unique on primitive values
$collectionArray = collect[1, 2, 2, 2, 3, 4, 4, 5];
$unique = $collectionArray->unique();
dd($unique); // Output: [1, 2, 3, 4, 5];
Example 2:
2. Unique on specific keys in arrays of objects
$collectionArray = collect([
['type' => 'A1', 'grade' => 'A' ];
['type' => 'B1', 'grade' => 'B' ];
['type' => 'C1', 'grade' => 'C' ];
['type' => 'A1', 'grade' => 'A' ];
]);
$uniqueValue = $collectionArray->unique('type');
dd($uniqueValue);
// Output:
// [
// ['type' => 'A1', 'grade' => 'A' ];
// ['type' => 'B1', 'grade' => 'B' ];
// ['type' => 'C1', 'grade' => C' ];
// ]
Example 3: Reset keys with values()
3. Reset keys with values()
$uniqueValue = $collectionValue->unique('type')->values();
dd($uniqueValue);
// Output:
// [
// 0 => ['type' => 'A1', 'grade' => 'A'];
// 1 => ['type' => 'B1', 'grade' => 'B'];
// 2 => ['type' => 'C1', 'grade' => 'C'];
// ]
Read also: Laravel Blade foreach loop example
Using the Unique() method in Laravel collections helps to duplicate values easily. I hope that example helps to retrieve uniqueness record.
I hope this tutorial help you.