Debug School

rakesh kumar
rakesh kumar

Posted on

Important Laravel Collection methods :

  1. Laravel Collection methods are:
  2. pluck()
  3. chunk()
  4. whereNotIn()
  5. avg()
  6. first()
  7. last()
  8. merge()
  9. max()
  10. min()
  11. filter()
  12. search()
  13. sum()
  14. map()
  15. every()
  16. flip()
  17. forget()
  18. isEmpty
  19. isNotEmpty

  20. How to filter null values from the array in Laravel?

  21. How to calculate average value of array in Laravel?

  22. How to create array in batch sizes in Laravel?

  23. How to flattern multi-dimentional to single array in Laravel?

  24. How to combine two array with key/value pair in Laravel?

  25. How to check if value in array meet given criteria in Laravel?

  26. How to perform multiple operations on array in Laravel?

Pluck()

$collection = collect([
     ['name' => 'test', 'email' => 'test@gmail.com'],
     ['name' => 'test1', 'email' => 'test1@gmail.com'],
 ]);
 $plucked = $collection->pluck('name');
 $plucked->all();

// Output  (Response) 

['test', 'test']
Enter fullscreen mode Exit fullscreen mode

Chunk()
Chunk method is used to split the collection into multiple into array.

 $tut = collect([a, b, c, d, e, f, g, h]);
 $tut = $tut->chunk(3)->toArray();
 // Output (Response)
 [
     0 => [
         0 => a,
         1 => b,
         2 => c
     ],
     1 => [
         3 => d,
         4 => e,
         5 => f
     ],
     2 => [
         6 => g,
         7 => h
     ]
 ]
Enter fullscreen mode Exit fullscreen mode

whereNotIn()
We can use whereNotIn method to filter the collection by a key value not contained within the given array.

 $collection->whereNotIn('product_id', [1, 2]);
Enter fullscreen mode Exit fullscreen mode

The above statement return response leave product_id 1,2. This is just opposite of wherein() method.

avg()
AVG method returns the average value. In this below collection avg method return to average of all numbers.

 $avg = collect([10, 20, 50, 30, 40]);
 $avg->avg();
 //Output (Response)
 30
Enter fullscreen mode Exit fullscreen mode

first()
first() method returns the first value of collection.

$first = collect([1, 2, 3, 4, 5]);
$first->first();
 // Output (Response)
 1
Enter fullscreen mode Exit fullscreen mode

last()
last() method returns the last value of collection. last method, just opposite of first method.

 $last = collect([1, 2, 3, 4, 5]);
 $last->last();
 // Output (Response)
 5
Enter fullscreen mode Exit fullscreen mode

merge()
merge() methods is used to merge two or more collection or array.

 $collection = collect(['1', '2']);
 $merged = $collection->merge(['3', '5']);
 $merged->all();
 // Output (Response)
 [1, 2, 3, 5]
Enter fullscreen mode Exit fullscreen mode

max()
max() method return the maximum value of given collection.

 $max= collect(['1', '2', '3', '4', '5', '6']);
 $max->max();
 // Output (Response)
 6
Enter fullscreen mode Exit fullscreen mode

min()
min() methods return the minimum value of given collection.

 $min= collect(['1', '2', '3', '4', '5', '6']);
 $min->min();
 // Output (Response)
 1
Enter fullscreen mode Exit fullscreen mode

filter()
filter() methods is used to filter the record from collection.

 $collection = collect(['1', '2', '3', '4', '5', '6', '7']);
 $filtered = $collection->filter(function ($value, $key) {
     return $value > 3;
 });
 // Output (Response)
 [4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

search()
search() method is used to search the collection for a given value. If the value is exist in the collection, return true. If the value does not exist in collection, return false.

 $collection = collect(['a', 'b', 'c', 'd', 'e', 'f', 'h']);
 $search = $collection->search(d);
 // Output (Response)
 4
Enter fullscreen mode Exit fullscreen mode

sum()
sum() method is very simple in collection and it is used to sum of the collection values.

 $collection = collect(['1', '2', '3', '4', '5', '6', '7']);
 $sum = $collection->sum();
 // Output (Response)
 28
Enter fullscreen mode Exit fullscreen mode

toArray()
toArray() methods is used to convert collection into simple php array()

 $collection = collect(['name' => 'test', 'email' => test@gmail.com, 'mobile' => '9876543210']);
 $collection->toArray();

 // Output (Response)
 [
   [
     'name' => 'test',
     'email' => test@gmail.com,
     'mobile' => '9876543210'
 ]
 ]
Enter fullscreen mode Exit fullscreen mode

map()
The map() method is one of my favorite one. This method will iterate on a collection and return value to a callback function which will form a new collection. In this callback function, you are free to modify the item and return it.

$products = Product::all();
 $newPrices = $products->map(function ($item, $key) {
     return $item['price'] * 2;
 });
 dd($newPrices);
 // Result will be
 Collection {#510 ▼
   #items: array:5 [▼
     0 => 699.9
     1 => 363.9
     2 => 299.98
     3 => 1359.98
     4 => 599.98
   ]
 }
Enter fullscreen mode Exit fullscreen mode

every()
The every() method will check every element of the collection for a given condition. For example, for our above collection:

$every = $products->every(function ($item, $key){
     return $item['price'] > 100;
 });
 dd($every); // true
 $every = $products->every(function ($item, $key){
     return $item['price'] > 300;
 });
 dd($every); // false
Enter fullscreen mode Exit fullscreen mode

flip()
The flip() method swap the collection keys with their values. Like below:

$products = collect(['name' => 'Blackberry', 'category' => 'phone']);
 $flipped = $products->flip();
 dd($flipped);
 Collection {#509 ▼
   #items: array:2 [▼
     "Blackberry" => "name"
     "phone" => "category"
   ]
 }
Enter fullscreen mode Exit fullscreen mode

forget()
The forget() method will remove an item from the collection by a given key.

$products = collect(['name' => 'Blackberry', 'category' => 'phone']);
 $products = $products->forget('category');
 dd($products);
 Collection {#514 ▼
   #items: array:1 [▼
     "name" => "Blackberry"
   ]
 }
Enter fullscreen mode Exit fullscreen mode

isEmpty()
The isEmpty() method will return true if the given collection is empty, otherwise it will return false.

 $products = Product::all();
 $products->isEmpty(); // false
Enter fullscreen mode Exit fullscreen mode

isNotEmpty()
The isNotEmpty() method will return true if the given collection is not empty, otherwise it will return false.

 $products = Product::all();
 $products->isNotEmpty(); // true
Enter fullscreen mode Exit fullscreen mode

How to filter null values from the array in Laravel?

// returns object of type Illuminate\Support\Collection

$collection = collect(['sandip', 'chintu', null]);

// loop through collection make all values uppercase
// use reject function reject array values that are empty
$array = $collection
->map(function ($value) {
        return Str::upper($value);
    })
    ->reject(function ($name) {
        return empty($name);
    })->toArray();

// print the array
dd($array);
Enter fullscreen mode Exit fullscreen mode

How to calculate average value of array in Laravel?

// create array to laravel collection object
$collection = collect([
    ['foo' => 10],
    ['foo' => 10],
    ['foo' => 20],
    ['foo' => 40]
]);

// print average of the collection array
dd($collection->avg());

// OUTPUT: 20
Enter fullscreen mode Exit fullscreen mode

How to create array in batch sizes in Laravel?

// create array to laravel collection object

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

// create array in batch of 5
$batches = $collection->chunk(5);

// display array with batches
dd($batches->all());

// OUTPUT: 
Enter fullscreen mode Exit fullscreen mode

** How to flattern multi-dimentional to single array in Laravel?**

// create multi-dimentional array to laravel collection
$collection = collect([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]);

// flattern all arrays into single
$collapsed = $collection->collapse();

// display single array
dd($collapsed->all());

// OUTPUT: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

** How to combine two array with key/value pair in Laravel?**

// create array that will be used as keys to laravel collection object

$collection = collect(['name', 'age']);

// supply array that will be used as values
$combined = $collection->combine(['Sandip', 29]);

// display values
dd($combined->all());

// OUTPUT: ['name' => 'Sandip', 'age' => 29]
Enter fullscreen mode Exit fullscreen mode

** How to check if value in array meet given criteria in Laravel?**

// create array to laravel object
$collection = collect([1, 2, 3, 4, 5]);

// check to see if values in array are greater then 5
$moreThenFive =$collection->contains(function ($value, $key) {
    return $value > 5;
});

dd($moreThenFive); // OUTPUT: false

// create array to collection object
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

// check to see product has value Table
dd($collection->contains('product', 'Table'));
Enter fullscreen mode Exit fullscreen mode

** How to perform multiple operations on array in Laravel?**

// create employee array to laravel collection

$employees = collect([
      ['email' => 'james@example.com', 'position' => 'Designer'],
      ['email' => 'abigail@example.com', 'position' => 'Developer'],
      ['email' => 'victoria@example.com', 'position' => 'Developer'],
]);

$employees
    // find duplicate positions
    // with total duplicate counts
    ->duplicates('position')

    // make values uppercase
    ->map(function ($value) {
        return Str::upper($value);
    })

    // get all values
    ->all()

    // dump given array
    ->dd();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)