Support the ongoing development of Laravel.io →
Article Hero Image

Top 10 Laravel Collection Methods You May Have Never Used

9 Jun, 2024 3 min read

Photo by Karen Vardazaryan on Unsplash

In this article series, we go a little deeper into parts of Laravel we all use, to uncover functions and features that we can use in our next projects... if only we knew about them!

Here are a few lesser-known collection methods that can be quite handy in various real-world scenarios:

  1. macro(): This lets you add custom methods to Laravel collections that can be used on any collection instance:

use Illuminate\Support\Collection;

Collection::macro('customMethod', function () {
    // Your custom method logic
});

$collection = collect([...]);
// use on any collection object
$result = $collection->customMethod();
  1. concat(): Suppose you have two collections of users from different sources and want to combine them into a single collection. You can use concat for this purpose:
$usersFromDatabase = User::where(...)->get();
$usersFromApi = collect([...]);

$combinedUsers = $usersFromDatabase->concat($usersFromApi);
  1. pad(): You have a collection of tasks, but you want to ensure that it always contains a minimum number of elements. You can use pad to add dummy tasks if necessary:
$tasks = collect([...]);

$paddedTasks = $tasks->pad(10, 'Dummy Task');
  1. shuffle() & random(): Suppose you have a quiz application and want to shuffle the order of the questions. You can use shuffle for this purpose. Additionally, if you're going to select a question from the collection randomly, you can use random:
$questions = collect([...]);

$shuffledQuestions = $questions->shuffle();
$randomQuestion = $questions->random();
  1. crossJoin(): Suppose you've two collections and you want to generate all possible combinations from them.
$collection = collect([1, 2]); 
$matrix = $collection->crossJoin(['a', 'b']); 
$matrix->all();
/*[
    [1, 'a'],
    [1, 'b'],
    [2, 'a'],
    [2, 'b'],
]*/

$collection = collect([1, 2]); 
$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']); 
$matrix->all();
/*[
    [1, 'a', 'I'],
    [1, 'a', 'II'],
    [1, 'b', 'I'],
    [1, 'b', 'II'],
    [2, 'a', 'I'],
    [2, 'a', 'II'],
    [2, 'b', 'I'],
    [2, 'b', 'II'],
] */

  1. partition(): Imagine you have a collection of students, and you want to partition them into two groups based on their grades (pass or fail). partition makes this easy:

$students = collect([...]);

list($passingStudents, $failingStudents) = $students->partition(function ($student) {

    return $student->grade >= 60;

});

  1. first() and firstWhere(): You have a collection of tasks, and you want to retrieve the first task or the first task that meets certain criteria. first and firstWhere come in handy:

$tasks = collect([...]);

$firstTask = $tasks->first();

$urgentTask = $tasks->firstWhere('priority', 'urgent');

  1. keyBy(): You have a collection of users, and you want to index them by their unique IDs for quick access. keyBy is the solution:

$users = collect([...]);

$indexedUsers = $users->keyBy('id');

  1. filter(): You have a collection of orders coming from API and you want to filter out the canceled orders. The filter method is perfect for this:

$orders = collect([...]);

$validOrders = $orders->filter(function ($order) {

    return $order->status !== 'canceled';

});

  1. transform(): You have a collection of tasks, and you want to modify each task in some way. transform allows you to apply a callback to each item to replace it:

$tasks = collect([...]);

$tasks->transform(function ($task) {

    return $task->name . ' - ' . $task->priority;

});


That's all for now, folks! These methods offer ease & flexibility that can be useful when working with Laravel applications.

All the above have been previously shared on our Twitter, one by one. Follow us on Twitter; You'll ❤️ it. You can also check the first article of the series, which is on Top 5 Scheduler Functions you might not know about. Keep exploring, keep coding, and keep pushing the boundaries of what you can achieve.

Last updated 3 weeks ago.

driesvints, ol-serdiuk, issacnguyentx2022 liked this article

3
Like this article? Let the author know and give them a clap!

Other articles you might like

Article Hero Image November 18th 2024

Laravel Custom Query Builders Over Scopes

Hello 👋 Alright, let's talk about Query Scopes. They're awesome, they make queries much easier to r...

Read article
Article Hero Image November 19th 2024

Access Laravel before and after running Pest tests

How to access the Laravel ecosystem by simulating the beforeAll and afterAll methods in a Pest test....

Read article
Article Hero Image November 11th 2024

🍣 Sushi — Your Eloquent model driver for other data sources

In Laravel projects, we usually store data in databases, create tables, and run migrations. But not...

Read article

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.