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.
“Tinkerwell allows me to prototype ideas in the most efficient way possible. I feel like my life was different before it.”Benjamin Crozat
Indie Hacker & Blogger
“Tinkerwell was a no-brainer from the very beginning. Finally no more test.php files or test routes in your Laravel application.”Stefan Bauer
Co-Founder of PingPing.io
The must-have companion to your favorite IDE. Quickly iterate on PHP code within the context of your web application.
Buy now Learn more