Tinkerwell 4 is out now! See what's new or buy now.
Tinkerwell background image
Tinkerwell Logo Tinkerwell
Go back to Blog

Laravel collection methods: filter() & sort()

Laravel Collections are a powerful feature and the framework uses them automatically in many situations. If you query an Eloquent model and get more than one result, the result is a collection instead of a simple array. Laravel does this to make processing the data simpler and providing a convenient layer on top of many array functions.

When working with Laravel Collections, Tinkerwell is a powerful helper and it allows you to see which collection method is the right one and makes a typical collection pipeline easy to write.

As a first example, we are wrapping an array with random numbers into a collection, filter this array and sort it ascending from the lowest to the highest number.

$numbers = [];
while(count($numbers) < 8) {
array_push($numbers, rand(1, 1000));
}
collect($numbers) //?
->filter(function($number) {
return $number > 500;
})
->sort();

This example uses the Magic Comments feature of Tinkerwell to display the content of the collection in line 5 inline and outputs the result in the output window at the bottom.

In a second scenario, we're fetching data from an API that has no filter or sort method and doing this with their collection methods.

This example uses the GitHub API to fetch all repositories of our Beyond Code organization as a Laravel collection. Afterwards, we apply a filter on the Laravel collection to filter the collection down to all repositories that have "laravel" in their name and sort them by the length of their name.

Http::get("https://api.github.com/orgs/beyondcode/repos")
->collect()
->filter(function ($repository) {
return str($repository["name"])->contains("laravel");
})
->sortBy(function ($repository) {
return str($repository["name"])->length();
})
->pluck("name");

As you can see, the filter and sort methods of collections in Laravel are pretty powerful. When you dig deeper into Laravel or are an experienced developer, you'll know that collections are all over the place and every time you fetch multiple models from a database, the result is a collection.

Jess Archer, Laravel Core team member
“Tinkerwell is the fastest way to test an idea or debug an application. It just keeps getting better and better!”

Jess Archer

Laravel Core team member

Mfawa Alfred Onen, Software Engineer
“I use Tinkerwell as my daily driver for prototyping different ideas and has become an even greater refactoring asset for most of my workflows. A tool like this is essential, period!”
Mfawa Alfred Onen

Software Engineer

Tinkerwell: The PHP Scratchpad

The must-have companion to your favorite IDE. Quickly iterate on PHP code within the context of your web application.

Buy now Learn more