DEV Community

Morcos Gad
Morcos Gad

Posted on

Collections ( reject - Unique ) - Laravel

Today we will take an idea of two old collections but very useful data in dealing with and filtering data and it will help you greatly in your next projects. We will quickly take some examples that will clarify the idea of their work.

  • Collection With reject

Example 1

$collection = collect([1, 2, 3, 4]);

$filtered = $collection->reject(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [1, 2]
Enter fullscreen mode Exit fullscreen mode

Example 2


use Illuminate\Support\Collection;
use Illuminate\Support\Str;

// Create a new collection instance.
$collection = new Collection([
    'Alice', 'Anna', 'Bob', 'Bev'
]);

// Only keep names that begin with the letter 'a'.
$names = $collection->reject(function($item), {
    return !Str::startsWith(Str::lower($item), 'a');
});

/* 
object(Illuminate\Support\Collection)
  protected 'items' =>
    array
      0 => string 'Alice'
      1 => string 'Anna'
*/
Enter fullscreen mode Exit fullscreen mode

Example 3 with map()

$names = $users->reject(function ($user) {
            return $user->active === false;
         })->map(function ($user) {
            return $user->name;
         });
Enter fullscreen mode Exit fullscreen mode
  • Collection With Unique

Example 1

$data = [1,2,4,5,3,2,2,4,5,6,8,9]; 
$data  = collect($data)->unique();  
dd($data);

/*
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
    [4] => 3
    [9] => 6
    [10] => 8
    [11] => 9
)
*/
Enter fullscreen mode Exit fullscreen mode

Example 2

$data = collect( [
            [
                [ "id" => 1, "name" => "Hardik"],
                [ "id" => 1, "name" => "Hardik"],
                [ "id" => 2, "name" => "Mahesh"],
                [ "id" => 3, "name" => "Rakesh"],
            ],
            [
                [ "id" => 1, "name" => "Hardik"],
                [ "id" => 3, "name" => "Kiran"],
            ]
        ] );

$data = $data->map(function ($array) {
       return collect($array)->unique('id')->all();
});   
dd($data);

/*
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Hardik
                )
            [2] => Array
                (
                    [id] => 2
                    [name] => Mahesh
                )
            [3] => Array
                (
                    [id] => 3
                    [name] => Rakesh
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Hardik
                )
            [1] => Array
                (
                    [id] => 3
                    [name] => Kiran
                )
        )
)
*/
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code and I wish you a happy code .

Top comments (0)