unique collection – Laravel Collection Get Unique Values Example

Rate this post

unique collection method can be used to get all the unique items in the collection. it’s part of the Enumerable contract.

unique collection

also you can safely use it to get a Collection instance. and then you can read my prev article like as Get Unique Collection Values(Remove Duplicates From Collection) Using Laravel

Example 1: Laravel Controller Code:

<?php
  
namespace App\Http\Controllers;
  
class PakaController extends Controller
{
    /**
     * Write code on Method
     * created by Pakainfo.com
     * @return response()
     */
    public function index()
    {
        $records = [1,2,4,5,3,2,2,4,5,6,8,9];
  
        $records  = collect($records)->unique();
  
        dd($records);
    }
}

Free Live Chat for Any Issue

Result

Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
    [4] => 3
    [9] => 6
    [10] => 8
    [11] => 9
)

Don’t miss : Laravel Sum Query with Where Condition Example

Read Also:  Laravel 5.7 Toggle switch Update DB field using Ajax

Example 2: Controller Code:

<?php
  
namespace App\Http\Controllers;
  
class PakaController extends Controller
{
    /**
     * Write code on Method
     * created by Pakainfo.com
     * @return response()
     */
    public function index()
    {
        $records = collect( [
            [
                [ "id" => 1, "name" => "Ridham"],
                [ "id" => 1, "name" => "Ridham"],
                [ "id" => 2, "name" => "Mayur"],
                [ "id" => 3, "name" => "Kishan"],
            ],
            [
                [ "id" => 1, "name" => "Ridham"],
                [ "id" => 3, "name" => "Keyur"],
            ]
        ] );
  
        $records = $records->map(function ($array) {
            return collect($array)->unique('id')->all();
        });
   
        dd($records);
    }
}

Result

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Ridham
                )
            [2] => Array
                (
                    [id] => 2
                    [name] => Mayur
                )
            [3] => Array
                (
                    [id] => 3
                    [name] => Kishan
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Ridham
                )
            [1] => Array
                (
                    [id] => 3
                    [name] => Keyur
                )
        )
)

Download

I hope you get an idea about unique collection.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.