Laravel Collections Tutorial - 15 Must know Laravel Collection Methods

Laravel Collections Tutorial - 15 Must know Laravel Collection Methods

We will review some of the best and must-know Laravel Collection methods to make your life easier working with Laravel: all(), avg(), each(), chunk(), contains(), count() & countBy(), filter(), get(), search(), groupBy(), max(), pluck(), forget(), toArray(), sortBy()

Laravel comes with very powerful and convenient wrapper for working with arrays. You must have used collections in Laravel specially while working with Eloquent. Eloquent returns the query results in custom Collection object ~ Eloquent Collection class is inherited from Laravel Collections therefore, it inherits all the powerful methods offered by Laravel Collection and on top, provides few more great methods to use.

Laravel collection methods

In this article, we will review some of the best and must-know Laravel Collection methods to make your life easier working with Laravel.

Note: Remember, Eloquent Collection inherits Laravel Base Collection class thus it has access to all of the Base Collection's methods but Base Collection object cannot access custom methods provided by eloquent collection.

Let's look at how you can create simple Laravel Base Collection Object:

$todocollection = collect([
    [
        'user_id' => '1',
        'title' => ‘Do Laundry,
        ‘description => ‘I ‘have to do laundry ‘
    ],
    [
         'user_id' => '1',
        'title' => ‘Finish Assignment,
        ‘description => ‘I have to finish Maths assignment ‘
    ],
]);

This is how you can create Laravel Collection object. You can use all the powerful methods provided by Laravel Collection.

Now, let's look at an example of Eloquent Collection object:

$todos = ToDo::where('user_id',1)->get();

Here, $todos is an eloquent collection object which contains query results. It is simply an array from inside with some powerful collection methods at your disposal. You can still use Laravel Collection methods but Eloquent Collection also provides additional methods. You can do various things like converting to array, filtering your collection, sorting, mapping etc.

Let's look at some of the best and must-know Laravel Collection Methods:

  1. all()
  2. avg()
  3. each()
  4. chunk()
  5. contains()
  6. count() & countBy()
  7. filter()
  8. get()
  9. search()
  10. groupBy()
  11. max()
  12. pluck()
  13. forget()
  14. toArray()
  15. sortBy()

1) all()

Laravel Collection class has a protected property called $items which contains an array with all the data. Collection wrapper provides additional methods to operate on that array. But if you simply want the array without all those bells and whistles then there is a method for that!

$emails = collect([
        ‘[email protected],
        ‘[email protected]’,
        ‘[email protected]’,
    ‘[email protected]’
    ]);

    $emails_array = $emails->all();

    dd($emails_array);

/*
Array:4 [▼
  0 => "‘[email protected]"
  1 => "[email protected]"
  2 => "[email protected]’"
  3 => “[email protected]”
]
*/

2) avg()

Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection. But, if collection contains key => value pair, then you can provide key to the function and it will automatically calculate the average of all values to that key.

$simple_collection = collect([2,5,7,35,25,10]);

$s_avg = $simplex_collection->avg();

// 14

$key_collection = collect(['score' => 98], ['score' => 90], ['score' => 70],['score' => 86]);

$key_avg = $key_collection->avg();

//86

3) each()

Each method for Laravel Collection is similar to map function on arrays in PHP and JavaScript. Each method basically takes each element from the collection and applies the callback function on it. This method can be used to apply operations on each element, modify each element etc.

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

$collection->each(function($item){
    return $item*$item;
});

// [1,4,9,16]

laravel php web-development programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Laravel Development Company

Skenix Infotech is a top Laravel Website Development Company with Expert Laravel Developers that provides robust Laravel Development Services at fair costs.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** has always been an industry leader for companies and business owners looking to hire...