Laravel

How to Remove Null and Empty Values from Laravel Collection

Laravel

How to Remove Null and Empty Values from Laravel Collection

Laravel Collections provide a powerful way to work with arrays of data in a more expressive and convenient manner. Sometimes, you might need to remove null and empty values from a collection to clean up your data. In this tutorial, we'll guide you through the process of removing null and empty values from a Laravel collection with an example.

Step 1: Create a Laravel Collection

Before we proceed, ensure you have a Laravel collection to work with. You can create a collection using the collect() function or by transforming an existing array into a collection.

For the purpose of this example, let's create a sample collection:

$collection = collect([
    'name' => 'John',
    'age' => null,
    'email' => '',
    'city' => 'New York',
    'country' => null,
]);

Step 2: Remove Null and Empty Values

To remove null and empty values from the collection, you can use the reject() method along with a custom callback function.

$filteredCollection = $collection->reject(function ($value, $key) {
    return $value === null || $value === '';
});

In this example, the reject() method iterates through each item in the collection and keeps only the items where the value is not null or empty.

Step 3: Display the Filtered Collection

You can now display the filtered collection to see the result.

$filteredCollection->each(function ($value, $key) {
    echo "$key: $value<br>";
});

This will output:

name: John
city: New York

Alternative: Use filter() Method

You can achieve the same result using the filter() method with the opposite condition.

$filteredCollection = $collection->filter(function ($value, $key) {
    return $value !== null && $value !== '';
});

Laravel Collections provide an elegant and efficient way to manipulate data, including removing null and empty values. By using the reject() or filter() method along with a custom callback function, you can easily remove unwanted values from your collections. This is particularly useful when you need to clean up and prepare your data for further processing or presentation.