Understanding Laravel Collections: `reject` vs. `map`
Salma
Posted on December 10, 2023
*Laravel Collections * provide a powerful and expressive way to work with arrays or sets of data. In this post, we'll explore two fundamental functions: reject
and map
. While both are essential tools in your Laravel toolkit, they serve distinct purposes in data manipulation.
The reject
Function:
The reject
function is your go-to tool for filtering out items from a collection based on a specified condition. It creates a new collection that excludes items for which the callback returns true
. Let's look at an example:
$collection = collect([1, 2, 3, 4, 5]);
$filtered = $collection->reject(function ($item) {
return $item % 2 == 0; // Exclude even numbers
});
dd($filtered->all()); // Output: [1, 3, 5]
In this example, we use reject
to create a new collection that excludes even numbers from the original collection.
The map
Function:
On the flip side, the map
function is your ally when you need to transform each item in a collection using a callback. It creates a new collection with the results of applying the callback to each item. Here's an illustration:
$collection = collect([1, 2, 3, 4, 5]);
$squared = $collection->map(function ($item) {
return $item * $item; // Square each number
});
dd($squared->all()); // Output: [1, 4, 9, 16, 25]
In this example, we use map
to create a new collection where each item is squared.
Key Differences:
-
Purpose:
-
reject
: Filters items based on a condition, excluding items that satisfy it. -
map
: Transforms items based on a callback, creating a new collection with the transformed values.
-
-
Result:
-
reject
: Returns a new collection with items that did not meet the specified condition. -
map
: Returns a new collection with items transformed according to the provided callback.
-
-
Callback Return Value:
-
reject
: Includes items for which the callback returnsfalse
. -
map
: Includes the results of applying the callback to each item.
-
In summary, while reject
is your tool for excluding items, map
is your friend for transforming them. Choose the right function based on your data manipulation needs.
Happy coding! 🚀
Posted on December 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.