Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Cleaning Null Values Safely in Laravel Collections

When a Laravel collection holds optional values, a later transformation may reject null. Remove nulls before that step if it expects a value. The right check depends on where the null appears: as a whole collection item, in a field on a record (an item with named fields), or in a field inside a record you want to keep.

To remove only nulls, use an explicit check such as filter(fn ($value) => $value !== null). A bare filter() also removes values such as false, 0, and an empty string. Choose the right filter and place it at the right point in the chain to keep valid data and make later steps predictable.

Remove only null items

Use a strict comparison when each collection item may itself be null:

$clean = collect($values)
    ->filter(fn ($value) => $value !== null);

The callback keeps every value other than null. For example, it keeps 0 and false, as well as '' and []. Laravel’s filter() removes values that evaluate as false when you call it without a callback. PHP’s array_filter() also removes the string '0' when called without a callback, and it preserves the keys of the values it keeps. See Laravel’s collection filtering behavior and PHP’s array_filter() documentation.

Use bare filter() only when the rule is to discard all falsy values. If zero, false, or an empty string has meaning in your data, the explicit null check avoids discarding it.

Filter records by a nullable field

When each collection item is a record and you want to discard records with a null field, use whereNotNull():

$withNames = $records->whereNotNull('name');

This removes records where name is null and keeps records where name is 0 or ''. Laravel removes each matching record as a whole, leaving the name field on records that remain. Laravel documents this behavior in its collection examples.

For arrays, decide whether a missing key counts the same as a key whose value is null. This predicate excludes records in either case:

$withNames = $records->filter(
    fn (array $record) =>
        array_key_exists('name', $record) && $record['name'] !== null
);

Use array_key_exists() when your data rule depends on that distinction. If records can be objects instead of arrays, write a predicate that checks their actual structure.

Filter before a step that requires a value

Check for null before a transformation that expects a non-null value:

$names = collect($values)
    ->filter(fn ($value) => $value !== null)
    ->map(fn (string $value) => trim($value))
    ->values();

This example assumes every remaining value is a string. The null check does not confirm that. If the collection can contain other types, Laravel 13.x provides ensure() to check each item’s type:

$names = collect($values)
    ->filter(fn ($value) => $value !== null)
    ->ensure('string')
    ->map(fn (string $value) => trim($value))
    ->values();

ensure() checks the remaining values and throws an UnexpectedValueException if a value does not match the allowed type. It does not remove invalid values. Check that your project’s Laravel version includes this method. PHP type declarations explain how declared parameter types limit the values passed to callbacks.

If the mapping step produces null, filter after mapping:

$results = $items
    ->map(fn ($item) => transformOrReturnNull($item))
    ->filter(fn ($result) => $result !== null)
    ->values();

A filter removes only the values present when it runs, so it cannot remove nulls that a later callback creates. Filter before the transformation when nulls come from the input; filter after it when the transformation creates nulls. For more on how chaining order affects results, see method order in Laravel collection chains.

Remove null-valued fields while keeping each record

To keep each record but remove its null-valued fields, filter the fields inside the record:

$cleanRecords = $records->map(
    fn (array $record) => collect($record)
        ->filter(fn ($value) => $value !== null)
        ->all()
);

The inner filter removes only fields whose values are null, so values such as 0, false, and '' remain. The call to all() returns each cleaned record as an array. Choose this when the output should omit null-valued fields. Turning an Eloquent model or another object into an array can change the representation that later code expects.

Preserve keys or reset them deliberately

Filtering can leave gaps in numeric keys. When a later step needs consecutive indexes starting at zero, call values() to reset the keys:

$list = collect([
    10 => 'A',
    11 => null,
    12 => 'C',
])
    ->filter(fn ($value) => $value !== null)
    ->values();

After filtering, values() resets the keys to 0 and 1. Keep the original keys when they identify records or carry meaning; call values() only when you want new indexes.

If a filter removes every item, Laravel’s first() returns null. Check whether the result is empty or provide a suitable default before relying on a value. The Laravel collection API documents these behaviors.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *