Dev Leak
Press ( / )
Subscribe Sign In
home Home popular Popular topics Topics mail Newsletter
Topic: Laravel Laravel Topic: Animation Animation Topic: Docker Docker Topic: Fundamentals Fundamentals Topic: Debugging Debugging Topic: Web Web
home Home popular Popular topics Topics mail Newsletter
Topic: Laravel Topic: Animation Topic: Docker Topic: Fundamentals Topic: Debugging Topic: Web
Five Ways to Use the Reject Method
10 min read

Five Ways to Use the Reject Method

Leveraging the Power of Laravel Collections: 5 Practical Applications of the 'Reject' Method

April 5, 2023

1k Views
david

david

20 Posts

mail-dark Newsletter

Five Ways to Use the Reject Method

Leveraging the Power of Laravel Collections: 5 Practical Applications of the 'Reject' Method

david

david

20 Posts

mail-dark Newsletter

April 5, 2023

1k Views

Say Thanks

Buy a Thanks, and directly support content like this.

Card Information

check-green Thank you for supporting! A receipt will be sent to your email

Laravel 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. The filter 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:

  1. $products is a Laravel Collection containing product objects. Each product object has a price attribute representing its cost.
  2. 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.
  3. Inside the closure, a condition is checked: $product->price > 100. If the current product price exceeds 100, the condition evaluates to true, and the reject method will consider this item for removal. If the condition is false, the item will remain in the resulting collection.
  4. 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:

  1. The reject method is called on the $allUsers collection, which contains all users.
  2. 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.
  3. 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.
  4. 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.
  5. If the contains method returns true, the current $user is an admin user. As a result, the reject 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:

  1. $emails is a Laravel Collection containing email addresses.
  2. 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.
  3. Inside the callback function, the filter_var() function validates each email address. The filter_var() function takes two arguments: $email: The email address being checked, and FILTER_VALIDATE_EMAIL: A constant representing the email validation filter.
  4. The filter_var() function returns the filtered data (in this case, the valid email address) if the email address is valid, and false otherwise.
  5. The ! operator negates the result of the filter_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 value false. Conversely, if the email address is invalid, filter_var() returns false, and the negation ! turns it into a truthy value true.
  6. 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.
  7. $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:

  1. $userData->reject(...): The reject method is called on the $userData collection, which will create a new collection by excluding elements based on the provided condition in the closure.
  2. function ($value, $key) {...}: The closure (anonymous function) passed as an argument to the reject method receives two parameters - $value and $key. $value represents the value of the current element in the collection, and $key represents its key.
  3. return is_null($key);: The closure checks if the current key $key is null using the is_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.
  4. $filteredData: The reject 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:

  1. $orders->reject(): The reject 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).
  2. 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.
  3. 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 returns true.
  4. 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.

unlocked-white Subscribe for exclusive content
Run Laravel Sail in PhpStorm Run Laravel Sail in PhpStorm
1 min

Run Laravel Sail in PhpStorm

david

2k Views 2 years ago

Run Laravel Sail in PhpStorm
2 min

Run Laravel Sail in PhpStorm

david

2k Views 2 years ago

Fixing Permission Errors with Laravel Sail
1 min

Fixing Permission Errors with Laravel Sail

david

2k Views 2 years ago

Five Clever Ways to Use the chunk Method
11 min

Five Clever Ways to Use the chunk Method

david

2k Views 2 years ago

Using Macros to Simplify Migrations
2 min

Using Macros to Simplify Migrations

david

1k Views 2 years ago

Run PhpUnit in PhpStorm Run PhpUnit in PhpStorm
1 min

Run PhpUnit in PhpStorm

david

1k Views 2 years ago

A String Helper for Apostrophes
2 min

A String Helper for Apostrophes

david

1k Views 2 years ago

3 Examples of When to Use @unless
5 min

3 Examples of When to Use @unless

david

1k Views 2 years ago

When to Use chunkWhile(): 5 examples
14 min

When to Use chunkWhile(): 5 examples

david

1k Views 2 years ago

Getting Started With Laravel and WSL2
2 min

Getting Started With Laravel and WSL2

david

1k Views 2 years ago

Blade Templates | All the Ways to Pass Data to views
9 min

Blade Templates | All the Ways to Pass Data to views

david

1k Views 2 years ago

Five Smart Ways to Use Collapse
11 min

Five Smart Ways to Use Collapse

david

1k Views 2 years ago

Choose your Sail Services
1 min

Choose your Sail Services

david

1k Views 2 years ago

A String Helper For Estimating Read Time
2 min

A String Helper For Estimating Read Time

david

1k Views 2 years ago

Setup PHPUnit in PhpStorm for a Laravel Project
1 min

Setup PHPUnit in PhpStorm for a Laravel Project

david

1k Views 2 years ago

5 Powerful Ways to Use the all() method
9 min

5 Powerful Ways to Use the all() method

david

1k Views 2 years ago

Five Ways to Use the Combine Method
11 min

Five Ways to Use the Combine Method

david

1k Views 2 years ago

WhereLikeIn() Helper
6 min

WhereLikeIn() Helper

Tricia Blosser

976 Views 1 year ago

Related

Run Laravel Sail in PhpStorm Run Laravel Sail in PhpStorm
1 min

Run Laravel Sail in PhpStorm

Run Laravel Sail in PhpStorm

david

2k Views 2 years ago

Topics

Laravel Animation
Run Laravel Sail in PhpStorm
2 min

Run Laravel Sail in PhpStorm

Streamlining Development with PhpStorm: Use your IDE to run Laravel Sail for a better experience.

david

2k Views 2 years ago

Topics

Laravel
Fixing Permission Errors with Laravel Sail
1 min

Fixing Permission Errors with Laravel Sail

Avoid Common Permission Errors with Laravel Sail

david

2k Views 2 years ago

Topics

Laravel Debugging
Five Clever Ways to Use the chunk Method
11 min

Five Clever Ways to Use the chunk Method

Harnessing the Power of the chunk() Method for Efficient Data Manipulation in Laravel Collections

david

2k Views 2 years ago

Topics

Laravel
Using Macros to Simplify Migrations
2 min

Using Macros to Simplify Migrations

How to add helper methods to the Blueprint Facade.

david

1k Views 2 years ago

Topics

Laravel
Run PhpUnit in PhpStorm Run PhpUnit in PhpStorm
1 min

Run PhpUnit in PhpStorm

david

1k Views 2 years ago

Topics

Laravel Animation
A String Helper for Apostrophes
2 min

A String Helper for Apostrophes

Effortlessly Converting Words to Possessive Forms with Laravel's String Class

david

1k Views 2 years ago

Topics

Laravel
3 Examples of When to Use @unless
5 min

3 Examples of When to Use @unless

When to use the @unless directive in Laravel's Blade Templates with three examples.

david

1k Views 2 years ago

Topics

Laravel
When to Use chunkWhile(): 5 examples
14 min

When to Use chunkWhile(): 5 examples

Mastering the ChunkWhile Method in Laravel Collections: 5 Practical Examples

david

1k Views 2 years ago

Topics

Laravel
Getting Started With Laravel and WSL2
2 min

Getting Started With Laravel and WSL2

Simplifying Laravel Development on Windows with WSL2 and Laravel Sail

david

1k Views 2 years ago

Topics

Laravel Docker Fundamentals
Blade Templates | All the Ways to Pass Data to views
9 min

Blade Templates | All the Ways to Pass Data to views

All the ways to pass data to Laravel Blade Templates: A comprehensive guide

david

1k Views 2 years ago

Topics

Laravel
Five Smart Ways to Use Collapse
11 min

Five Smart Ways to Use Collapse

Smart Ways to use the Collapse Method in Laravel Collections: 5 Practical Examples

david

1k Views 2 years ago

Topics

Laravel
Choose your Sail Services
1 min

Choose your Sail Services

Customizing Your Laravel Application with Sail: Selecting and Configuring Services for Your Docker-Compose File

david

1k Views 2 years ago

Topics

Laravel
A String Helper For Estimating Read Time
2 min

A String Helper For Estimating Read Time

Enhancing User Experience with a Custom Reading Time Estimator in Laravel

david

1k Views 2 years ago

Topics

Laravel
Setup PHPUnit in PhpStorm for a Laravel Project
1 min

Setup PHPUnit in PhpStorm for a Laravel Project

Setup PHPUnit in PhpStorm for a Laravel Project

david

1k Views 2 years ago

Topics

Laravel
5 Powerful Ways to Use the all() method
9 min

5 Powerful Ways to Use the all() method

Harnessing the Power of the all() Method for Efficient Data Manipulation in Laravel Collections

david

1k Views 2 years ago

Topics

Laravel
Five Ways to Use the Combine Method
11 min

Five Ways to Use the Combine Method

Leveraging the Power of Laravel Collections: 5 Neat Ways to Use the 'Combine' Method

david

1k Views 2 years ago

Topics

Laravel
WhereLikeIn() Helper
6 min

WhereLikeIn() Helper

Create a macro that loops through columns and search term strings on a Database Eloquent Builder.

Tricia Blosser

976 Views 1 year ago

Topics

Laravel
popular Popular topics Topics mail Newsletter

Footer

Dev Leak

Membership

  • Login
  • Newsletter
  • Subscribe

Support

  • Contact

Pages

  • Home
  • Search
  • Popular
  • Topics

Legal

  • Privacy Policy
  • Terms of Service

© 2025 DevLeak. All rights reserved.