Five Ways to Use the Reject Method
Leveraging the Power of Laravel Collections: 5 Practical Applications of the 'Reject' Method
April 5, 2023
1k ViewsLaravel Collections provide a convenient, fluent and easy-to-understand wrapper for working with arrays of data. One of the powerful methods that Collections offer is the reject
method.
The
reject
method excludes elements that meet a condition. Thefilter
method includes them.
The reject
method lets you filter out elements from a collection based on a specific condition, returning a new collection without the rejected elements. This article explores five common use cases for the reject
method in Laravel Collections.
What is the reject
method and how is it different than filter
?
The reject
and filter
methods in Laravel Collections are two sides of the same coin. Both selectively process elements in a collection based on a specific condition. While they share similarities, their primary distinction lies in their contrasting approaches to handling elements that meet the specified condition.
As the name suggests, the reject
method excludes or "rejects" elements that meet the given condition. In other words, it creates a new collection by retaining only elements that do not satisfy the condition.
On the other hand, the filter
method operates oppositely by retaining only the elements that meet the specified condition. It "filters in" the elements that pass the condition and creates a new collection.
Let's consider an example to illustrate the difference between the reject
and filter
methods. Assume we have a collection of integers and want to process only even numbers.
Using the filter
method, we would retain the even numbers in a new collection:
$evenNumbers = $numbers->filter(function ($number) {
return $number % 2 == 0;
});
Using the reject
method, we would exclude the odd numbers, resulting in a new collection containing only even numbers:
$evenNumbers = $numbers->reject(function ($number) {
return $number % 2 != 0;
});
The reject
method in Laravel Collections is the opposite of the filter
method in that it discards elements meeting a specific condition, whereas the filter
method retains them. Both methods are powerful tools for handling data, and developers can choose between them depending on their requirements and preferred approach.
1. Removing Elements Based on a Specific Attribute
In many applications, you may need to filter out items based on a specific attribute. You can exclude items that don't meet your requirements using the reject
method.
For example, let's say you have a collection of products and want to remove all products with a price higher than a certain threshold. You can achieve this with the following code:
$filteredProducts = $products->reject(function ($product) {
return $product->price > 100;
});
The reject
method is being used on a Laravel Collection $products
to create a new collection of products $filteredProducts
that have a price of 100 or less. Let's break down the code step by step:
-
$products
is a Laravel Collection containing product objects. Each product object has aprice
attribute representing its cost. - The
reject
method is called on the$products
collection. This method takes a closure (anonymous function) as an argument. The closure has a single parameter,$product
, representing each product object in the collection as it iterates through the items. - Inside the closure, a condition is checked:
$product->price > 100
. If the current product price exceeds 100, the condition evaluates totrue
, and thereject
method will consider this item for removal. If the condition isfalse
, the item will remain in the resulting collection. - The
reject
method creates a new Laravel Collection,$filteredProducts
, which contains only products priced at 100 or less. This new collection is derived from the original $products collection by excluding the items that met the condition in the closure.
2. Removing Elements That Match Another Collection
At times, you may need to remove items from a collection that are also present in another collection. The reject
method can help you achieve this efficiently.
Suppose you have two collections of users: one containing all users, and another containing only admins. To get a collection containing non-admin users, you can use the reject
method:
$nonAdminUsers = $allUsers->reject(function ($user) use ($adminUsers) {
return $adminUsers->contains($user);
});
In this example, a new Laravel Collection, $nonAdminUsers
, is being created by using the reject
method on an existing collection called $allUsers
. The purpose of this code is to filter out users who are present in the $adminUsers
collection, leaving only non-admin users in the new $nonAdminUsers
collection.
Let's break down the code step by step:
- The
reject
method is called on the$allUsers
collection, which contains all users. - A closure (anonymous function) is passed as an argument to the
reject
method. The closure takes a single$user
parameter, representing each individual user in the$allUsers
collection. - The use keyword allows the closure to access the
$adminUsers
collection from the outer scope. This makes it possible to use the$adminUsers
collection inside the closure for comparison purposes. - Inside the closure, the
$adminUsers->contains($user)
expression checks if the$adminUsers
collection contains the current$user
. The contains method returns a boolean value: true if the user is found in the$adminUsers
collection and false otherwise. - If the
contains
method returns true, the current$user
is an admin user. As a result, thereject
method excludes this user from the new$nonAdminUsers
collection. If it returns false, the user is not an admin and will be included in the$nonAdminUsers
collection.
3. Excluding Elements That Fail a Custom Validation
In some cases, you may want to exclude elements that fail to pass a custom validation. The reject
method can assist you in filtering out invalid elements from the collection.
Imagine you have a collection of emails, and you want to exclude all invalid email addresses:
$validEmails = $emails->reject(function ($email) {
return !filter_var($email, FILTER_VALIDATE_EMAIL);
});
In this example, the reject
method is being used to create a new Laravel Collection of valid email addresses by filtering out invalid ones from an existing collection of email addresses.
Here's a step-by-step explanation about the example:
-
$emails
is a Laravel Collection containing email addresses. - The
reject
method is called on the$emails
collection, and a callback function (closure) is provided as an argument. This callback function is executed for each email address in the$emails
collection. - Inside the callback function, the
filter_var()
function validates each email address. Thefilter_var()
function takes two arguments:$email
: The email address being checked, andFILTER_VALIDATE_EMAIL
: A constant representing the email validation filter. - The
filter_var()
function returns the filtered data (in this case, the valid email address) if the email address is valid, and false otherwise. - The
!
operator negates the result of thefilter_var()
function. If the email address is valid,filter_var()
returns the email address, which is considered a truthy value. The negation!
then turns it into a falsy valuefalse
. Conversely, if the email address is invalid,filter_var()
returns false, and the negation!
turns it into a truthy valuetrue
. - The
reject
method filters out elements for which the callback function returns a truthy value. In this case, invalid email addresses will result in a truthy value, so they will be excluded from the new collection. -
$validEmails
is assigned the resulting new Laravel Collection containing only valid email addresses after filtering out the invalid ones.
4. Removing Elements by Key
The reject
method can also be used to remove elements based on their keys. This is particularly useful when working with associative arrays.
For instance, you have an associative array of user data, and you want to exclude all elements with a null
key value:
$filteredData = $userData->reject(function ($value, $key) {
return is_null($key);
});
In the example, the reject
method is being used to filter a Laravel Collection called $userData
. The goal is to remove any elements in the collection whose keys are null.
Here's a breakdown of what is happening:
-
$userData->reject(...)
: Thereject
method is called on the$userData
collection, which will create a new collection by excluding elements based on the provided condition in the closure. -
function ($value, $key) {...}
: The closure (anonymous function) passed as an argument to thereject
method receives two parameters -$value
and$key
.$value
represents the value of the current element in the collection, and$key
represents its key. -
return is_null($key);
: The closure checks if the current key$key
is null using theis_null()
function. If the key is null, the function returns true, indicating that the element should be rejected (excluded from the new collection). If the key is not null, the function returns false, implying that the element should be retained in the new collection. -
$filteredData
: Thereject
method returns a new collection containing only the elements that did not meet the rejection condition (i.e., elements with non-null keys). This new collection is then assigned to the variable$filteredData
.
5. Excluding Elements Based on Complex Conditions
In more complex scenarios, you might need to filter out elements based on multiple attributes or conditions. The reject
method allows you to define a closure that handles these conditions with ease.
For example, you have a collection of orders, and you want to remove orders that have a status of 'cancelled'
and a total amount less than 50:
$filteredOrders = $orders->reject(function ($order) {
return $order->status == 'cancelled' && $order->total < 50;
});
In this example, the reject
method is being used to filter a Laravel Collection named $orders
. The purpose of this code is to create a new collection, $filteredOrders
, containing only the orders that do not meet the specified condition. In this case, the condition is checking if an order has a status of 'cancelled'
and a total amount less than 50
.
Here is an explanation of the code:
-
$orders->reject()
: Thereject
method is called on the$orders
collection. This method will create a new collection by excluding the elements that meet the condition defined within the provided closure (function). -
function ($order)
: The closure (anonymous function) is defined with a single parameter,$order
. This function will be executed for each element in the$orders
collection, and the current element being processed will be passed as the$order
parameter. -
return $order->status == 'cancelled' && $order->total < 50;
: Within the closure, the condition checks if the$order
has a status property equal to'cancelled'
and a total property less than 50. If both conditions are met, the closure returnstrue
. - When the
reject
method processes each$order
in the collection, it evaluates the closure's return value. If the closure returns true for an order, that order is "rejected" and not included in the resulting$filteredOrders
collection. Conversely, if the closure returns false, the order is retained in the new collection.
Wrapping Up
The reject
method in Laravel Collections is a powerful and versatile tool for filtering out unwanted elements based on various conditions. These five use cases demonstrate just a fraction of its potential applications. By understanding and utilizing the 'reject
method, you can streamline your code, improve readability, and build more efficient applications with Laravel.