Since Laravel v5.5.29 you can group collections by multiple levels. Let's see what this means and how this works.
Arrange
So this article is about a new feature in Laravel. But before we check that out, let's see how it worked before. groupBy is a method of the Collection class. For our examples I will create some data to work with. Students will be a factory state of the given User class.
This new state will add some data to the users. We have a new skilllevel and a teacher value. For our examples we will use a simple route callback. This way we can easily return the result in the browser.
I said something like because we are using the Faker package in our factory. So every result will look different. Next we use the groupBy method, to group our data by the skilllevel.
Till here, nothing is really new. So what is the new feature I was talking about? Patrizio T. made a pull request so that you're able to group collections by multiple levels. Let's take a look at an example for a better understanding of what that means.
We are passing an array instead of a string to define multiple levels. First the students should be grouped by the skilllevel and then by the teacher. So this is what we get:
This grouping can be helpful when you want to display or compare the data. In this case only Markus has a professional student. Maybe he is already a better teacher?
Going crazy
It wouldn't make sense for our case but we could group the students by their name and email as well.
I really like how simple it is now to group a collection by multiple values. The syntax is straight forward and it works really well. Do you got other good examples for this new feature? Let me know about it on Twitter.