Laravel Collections Tutorial


Let’s take an adventure on a Laravel collections tutorial. Having used the Laravel framework for some time, I’ve gotten used to working with the various features of it. One of the things I’ve been meaning to really dig into is the Collections aspect of Laravel. You’ll be dealing with laravel collections all the time, and up until this point, maybe you’re like me and just kind of figured out what you needed as you went. No longer! We will now become professional Laravel Collection masters by taking the deep dive, doing the double click, digging in, or whatever other buzzphrase you’d like to use into Laravel Collections.

The Collection Class

Before we even start to look at all the methods we can use, let’s look at the class file itself. We can see it has all of these use statements at the top.

So what do all these mean, and where do they come from? Well, let’s hit them one by one. First up, we have use Countable;. With PHP Storm, we can use the handy tool “Go To Declaration” to see.

use countable

This takes us to SPL.php and shows us the Countable Interface.

countable interface

Pretty cool! We can see that The Countable interface is part of the Standard PHP Library (SPL). By using this technique, we can decipher all of these use statements.

Standard PHP Library

use Countable

use ArrayIterator

use CachingIterator

use InvalidArgumentException

JSON PHP Extension

use JsonSerializable

PHP Predefined Interfaces and Classes

use ArrayAccess

use IteratorAggregate

Illuminate Contracts Interface

use Illuminate\Contracts\Support\Jsonable

use Illuminate\Contracts\Support\Arrayable

Also note that the Collection class lives in the Illuminate\Support namespace. Great, we got the administrative stuff out of the way and we know what it all means.

Trying The Laravel Examples

The Laravel documentation is fantastic, and we will use it as a guide for this collections tutorial. In reading the docs, we can see that in order to create a collection, we can use the convenient collect helper to do so. Now being that I’m not that great at accepting that things just work, when I don’t know how they work, I must even dig into how this helper works. If we put our detective cap on, we can see it comes right from this piece of code here.

The helpers.php file has a use Illuminate\Support\Collection; statement at the top, so our helper function is able to new up a Collection for us using this snippet.

New Up A Collection

With our new found knowledge of this convenient helper function, let us now new up a Laravel Collection for fun and profit.

As you can see, we now have a collection that we can work with. One of the first things to be explained in the documentation is how to map over each element in the collection and apply a function to it while rejecting values that do not specify a certain criteria. Using this example, let's have a look at our own collection of sites. We will change the format of all url's to include a www prefix while removing any url that contains the word facebook. Let's try it.

Cool! Note that in this iteration, we make use of the fluent interface. What does it mean to be fluent? All that means is you can chain together commands to get to the desired result. It’s kind of like chaining methods in jQuery. We apply two methods to the collection to achieve our desired result. map and reject. Inside the map iteration, we apply the str_replace function to each collection element, stripping the http:// and replacing with http://www. During the reject iteration we use the Laravel helper method str_contains to filter out any elements that contain the word facebook. Note that the expression must be equal to true in order for the reject method to eliminate the element. So we can almost read this as, if string contains facebook then reject it. We can see from the screenshot above that we did get our desired result.

The Laravel Collection Methods

With a basic grasp of what a Laravel collection is, let us now go through all of the available methods one by one.

1. all()

The Collection class has a protected property named $items which holds an array. This is what the Collection is built up from. The all() method simply returns that property. This is handy if you want to change a Laravel collection into a native PHP array.

Testing this on our own little collection, we can see that we are returned the array from which the collection is based like so.

2. avg()

The avg method does exactly what you think it would do, it calculates the average of a collection. Here is the code which powers it.

We can make use of it on a strictly numeric collection like so.

You can also provide a key for which to apply the average to. In the example of an associative array, you would need to do this.

The average Starbucks visit will cost you $3.56.

3. chunk()

I never found much use for chunk until I actually read the documentation, which has a great use case. As you would expect, chunk takes a group of things and breaks that group down into smaller groups. The use case the documentation mentions is dealing with a Bootstrap grid for example. If you’ve ever had a grid full of items, and find yourself looping through a result set and then checking the value of an iterator in order to determine where to terminate a row – this one is for you! In fact this one is for me, since I do this all the time! Instead of troubling yourself with this, just use chunk() instead. This is how it works.

Note the use of the PHP array_chunk() function.

Testing it for ourselves yields these results.

When looping over chunked results, note that you will need a nested foreach since you now have a collection, of smaller collections. So you need to loop through each chunk, then loop through the contents of each chunk individually.

4. collapse()

This method makes use of a static method call as we see here.

The code it is referencing is here.

Take special note of the array_merge() PHP function.

Here is our quick little test of collapse.

Before the collapse.

After the collapse.

5. contains()

How many times do you need to check if an array contains a value? All the time, am I right?! The handy contains method on Laravel Collections makes it easy to do when working with an array that has been collectionified.

The contains code.

First off, we can see the code makes use of the native PHP func_get_args(). The data_get() method is a custom helper method in the illuminate framework. Finally, we can see in_array() being put to use. Visit each of the prior links in turn to make sure you understand each step of the process.

Testing out contains() with the following collection.

It appears the contains method is only checking the value, not the key of the collection.

By passing an empty string as the second parameter, you can check for the existence of a specific key.

You may pass in two parameters in a case sensitive manner to check for the existence of a key value pair. Note that this only pertains to nested collections, so the snippet above works, but the snippet below does not.

To get a little more granular, you can just make use of your own callback function. Check it out.

There is no key by the name of hiphop in our collection. We do however have an NSX value in the collection, hence the truthy return. This also allows us to search for a key value pair in a flat collection like so.

6. count()

Simple but useful, count does precisely what it says, it counts the number of items in the collection. How does it work? Just like so.

The method uses the native PHP count() function. So in the Laravel Collection class, we simply look at the $items property, and return the number of items in it. Observe our example.

7. diff()

This method makes use of array_diff() to compare arrays. This is the code that makes it work.

For example, imagine a candidate has an array of companies she would like to work for. She needs to compare this against an array of companies that are currently not hiring, then try to interview with only those that are hiring. How might she do this?

8. each()

This method allows you to apply a callback to every item in the collection and is powered with this code.

For an example we will have a collection of numbers. As long as the number is less than 5, then we will use a callback to square it.

The same result with a foreach would be carried out like so:

So you see, each() just adds some sugar so you can code in a more modern style if you prefer. Pick your poison.

9. every()

This interesting method peeks into your collection and creates a new collection on every n’th element which you specify. The source is here.

As we test out the every method, we can see how it works.

By passing in an offset, we can change the starting point for counting.

10. filter()

The filter method is another one which allows you to apply a callback to the collection, retaining only the items that pass a test of your choice. The code which makes it happen is here.

As we can see it makes use of the native PHP function array_filter(). Taking the filter method for a test drive gives us these results.

Here, we basically say, only return the items which contain the string of ‘lemon’, and in fact this is exactly what we get.

11. first()

The first() method returns the first item in the collection. The source code for this method is here.

An example of first() in action.

As we can see in this example, the very first item in the collection which is an array, is returned to us. This method also allows you to specify a condition or truth test so you can return the first item that passes that test. In this next snippet we will check if an item is a string, and if so, return it.

12. flatten()

If you have a heavily nested multi dimensional array, you can use flatten() to turn it into a single dimension array. Consider this collection.

Before flatten()

After flatten()

Here is the code, which makes use of a static method call.

Note the use of the native PHP function array_walk_recursive().

13. flip()

flip() is used to take the keys of a collection, and swap them with their associated values. Let’s see what happens if we try to flip our prior collection.

We see this can only operate on string or integer values, so let’s give both of those a shot.

Now we are in business, it is working like a champ.

This method of course makes use of array_flip() and the code which shows us this is here.

14. forget()

With this method you can Fuhgettaboutit, pronounced (Fuh-Get-About-It). You pass in the key of the item to remove, and it does so.

Examining how this method works shows us this code here.

Which makes use of unset as we see here.

15. forPage()

This interesting method makes use of array_slice() as we can see by doing some detective work on the Collection class file below.

What it does is pretty cool. In a large result set that may be paginated, you can fetch the items from any page of the results. Say you have 5 pages of 5 items each. You could specify that you only want the results which would appear on page 3. Let’s see how to do that.

Very Cool!

16. get()

This is one of those methods you’ve been using all along without even thinking about it. get() simply gets the item you specify by key and returns null if the key is not there. It is powered via the following source code and makes use of the native PHP array_key_exists() function.

Consider the prior example where we had a list of 25 urls. The collection consisted of an array or arrays. Every inner array uses ‘url’ as it’s key, so we can’t get by that. We can however provide an integer, and that will get the item indexed at that value. Let’s try to get from our prior example.

Bingo – it works. A simpler example might be something like this.

17. groupBy()

You can pass a string or a callback to the groupBy method, and it will return to you the results, grouped by that value. Let’s test this out using the string approach. We will reconfigure our list of urls and change each key so that we have each url belonging to a certain type of category. They we can use the groupBy method to get by category.

I always found groupBy type operations to be a little tricky and hard to predict. The source code shows that this is indeed a bit of a more complex operation.

18. has()

We now have a simple one following the more complex example just above. Need to check if a key exists in your collection? Simple, just use has().

The source shows us how this works.

19. implode()

You’re probably used to taking an array in native PHP and imploding it into a list or line of items separated by some random character or group of characters. You can do the same thing to your collections with this method. Let’s see an example.

It works just like you think it would, making use of the native PHP implode().

20. intersect()

This method makes use of array_intersect() as we can see here from the source which computes the intersection of arrays.

We can also compute the intersection of collections, let’s see an example.

21. isEmpty()

Many times a collection is passed to a view, and you do not want to try to loop through it if it is empty. This handy method lets us know right away whether or not a collection even has anything inside of it. Let’s see how it works.

The source shows us how it makes use of PHP’s empty() function.

22. keyBy()

By looking at the source code of this method, we can see it makes use of the valueRetriever() method so let’s take a look at that.

Once again we see that reference to the data_get() method, and it’s a bit of a doozy so let’s inspect it.

This method looks to be one of the workhorses of the Collection class, and as we can see makes use of is_null(), is_array(), array_key_exists(), isset(), and is_object() among others.

An example of how keyBy() works shows that you can set the keys of the collection by the key provided to keyBy(). Observe.

23. keys()

This handy method gives you the ability to fetch only the keys of the collection. Let’s test it out on one of our mixed type collections.

An inspection reveals a call to array_keys().

24. last()

If you would like access to the last item in the collection, you can use the aptly named last() method. A few examples are in order. First we will pass no argument, which simply grabs the last item in the collection no matter what. The second example will use a callback to find the first item starting from the end of the collection that matches a given test.

25. map()

With this method we can iterate across the collection and pass each item to a callback which can modify it. Let’s see how it works.

Here is the source for map() which makes use of array_keys() and array_map().

26. merge()

We can see that merge() makes use of array_merge() here.

Testing it out on a couple of collections shows us how this works.

27. pluck()

One of my favorites is the pluck method which allows you to get all of the values for a provided key in the collection. Let’s test it out.

The source which makes pluck() possible.

28. pop()

Pop goes the weasel right off the end of the collection. In other words, pop() removes the last item from the collection.

We can see the use of array_pop() to help us out from the source.

29. prepend()

In order to add something to the beginning of an array, we usually use array_unshift(). The prepend() method uses a much friendlier name to give us an indication of what it will do. Testing it out gives us these results.

A quick source inspection does confirm the use of array_unshift() for us.

30. pull()

Let’s put pull() to the test straight away.

pull() takes an item out of the collection and returns it to you based on the key you provide to it. It uses this code to work it’s magic.

31. push()

Again you are most likely familiar with array_push() to put things on the end of an array. The laravel push() method allows us to put things on the end of a collection. Would you like to see?

Digging into the source gives us an indication of how this works.

32. put()

put() is almost like push() with a slightly different implementation. With put(), it also uses the offsetSet() method, but uses a different signature.

Testing this out shows us the difference in how this works.

By this example, you can see that we can overwrite existing values anywhere in the collection if we like – or simply add a new item both key and value altogether.

33. random()

random() allows us to reach into the collection and pull out a completely unpredictable and random item. A quick look at the source shows us how it completes this task.

You have a fair bit of logic happening there between the use of array_rand(), array_intersect_key(), and array_flip(). Let’s test it out.

34. reduce()

This method is like a recursive iteration down to one item in the collection using PHP’s array_reduce() function. We determine as much by viewing the source.

Along with a quick test.

35. reject()

We saw an example of this method at the beginning of the article when we rejected any url from the collection with a string value of facebook within it. Let’s look at the source to see how this works.

Testing it out again, and this time we will reject any item in the collection that contains the string ‘discover’.

36. reverse()

The reverse() method does what you expect and that is to reverse the order of the items in the collection. It does so using array_reverse() as we can see here.

Don’t forget, all of these methods are fluent so let’s remind ourselves of that now.

37. search()

Conveniently enough, you can also search through a given laravel collection using the handy search() method. It searched by value, and returns the key if found. The function uses array_search() and call_user_func() functions to make the magic happen.

Our test shows it working in action.

38. shift()

shift() is a nice little wrapper for array_shift() which grabs the first element off the start of an array.

Does it work? You betcha. Again, note the fluent style.

39. shuffle()

Makes it convenient to use the fluent style via the built in PHP shuffle() function.

Here is our own little test.

40. slice()

array_slice() is commonly used in many PHP projects. Laravel includes this in its collection class via the following code.

This method is very powerful. You are able to pass in a single value to determine where the slice will begin. At that point, it will return the rest of the items in the collection beginning from that point you provided. When I think of slice however, I usually think of it to mean when you reach into an array or collection, and take out a specific number of items at a specific starting point. You can do this as well with slice(), all you have to do is pass the number of items you would like as the second argument. Finally, you also have the option to either have brand new numeric based keys on the new slice, or the ability to retain the original keys. Pass true as the third argument if you want to keep the original keys in tact. Let’s test all three at once (note we pass all three parameters).

41. sort()

You can sort your collections using the sort() method. The Laravel code which powers it uses uasort() as you can see here.

Here we can see it in action.

42. sortBy()

This method is really handy to use with Eloquent, since we so often need to sort data from a database. The source is involved, so take a few minutes to review.

Testing out sortBy() shows it working great.

43. sortByDesc()

One of my personal favorites oddly enough, sort the results just like sortBy() but in the opposite direction.

44. splice()

splice() is powered by the PHP array_splice() function as seen here. This allows you to remove an item or items from the collection and replace with something else.

We can test this out as we remove two items beginning at index 3 and replacing the hole left with two new urls.

45. sum()

A quick and easy summing method you can use like so.

When you have nested arrays or objects, just pass the key you want to sum by.

46. take()

When you have a huge collection on your hands and only need a limited amount of items, take() is your friend. Got 100 items and only need 5? take(5). Maybe you need to lose a pound or two. Take only the first two from our prior example.

47. toArray()

Sometimes you might get stuck working with a collection problem that you can’t figure out. When you need to drop down to a plain old PHP array, you can use toArray() to do so.

Note the result is an array not a collection.

48. toJson()

You may also convert to JSON easy as pie.

49. transform()

With transform() you can modify the collection directly by iterating over it with a callback.

50. unique()

unique() is another method I rather enjoy. It will return only the unique values in the collection using this code here.

A quick test shows us it’s mastery in action.

51. values()

This is a cool little method that returns the collection with the keys set to incrementing numbers.

First without values()

Now with values() applied.

52. where()

This is nice method you can use for finding a key value pair in your collection. Note this is not the same as the database related where() as it can to employ operators such as greater than, less than, like, etc. Let’s test it out.

53. zip()

Finally we have the zip() method which combines values of a provided array with the values of your collection where index positions are equal. Let’s add a warranty to all the cars from our prior example as a test.

The Motivation For This Tutorial

It seems that when you’re using Laravel, certain things keep coming up over and over again. The first thing is certainly the architecture the framework uses, service providers, and understanding how the inversion of control container works. There are a few core things we all try to have under our belt. It seemed like collections were next up as far as something that it would be worth having a really solid grasp of. What better way to learn it than to complete the mega laravel collections tutorial!? In addition, it’s always really enlightening to look under the hood at the source to see how the magic happens. Having an understanding of the tool or framework you use gives confidence.

Summary and Further Reading

  • There are a lot of links in this tutorial that link right to the PHP functions that are used to create the Collections class. Read up on them, or review them – you might learn a thing or two or simply refresh your memory on a concept you had forgotten about.
  • While we covered plain vanilla laravel collections here, make sure to check out Dayle Rees tutorial on Eloquent Collections. It’s the best one I’ve seen.
  • If you don’t have a Laracasts subscription already, go get one and review their tutorial on Collections, it is fantastic.
  • Jens Segers has this awesome tutorial about laravel collections, do read through it!
  • Eric Barnes has some great resources for collections at laravel news as well.
  • Stupid Collection Tips (which are actually really cool!) by Jeff Madsen

And with that, our Laravel Collections Tutorial is complete!