Nullify is a plain PHP class to convert empty data of any type to null. Usage use MichaelRubel\Nullify\Nullify; Nullify::the($value); Note: the class checks also nested https://www.php.net/manual/en/function.is-iterable.php and https://www.php.net/manual/en/class.arrayaccess.php objects. Examples $value = null; Nullify::the($value); // null $value = ''; Nullify::the($value); // null $value = []; Nullify::the($value); // null $value = (object) []; Nullify::the($value); // null $value = new \stdClass; Nullify::the($value); // null Check nested elements: $values = new Collection([ 'valid' => true, 'empty_array' => [], 'empty_string' => '', 'collection' => new Collection([ 'invalid' => new \stdClass, ])]); Nullify::the($values); // Illuminate\Support\Collection^ {#459 // #items: array:4 [ // "valid" => true // "empty_array" => null // "empty_string" => null // "collection" => Illuminate\Support\Collection^ {#461 // #items: array:1 [ // "invalid" => null // ] // #escapeWhenCastingToString: false // } // ] // #escapeWhenCastingToString: false // } If you use https://laravel.com/docs/master/collections, you can make a macro: Collection::macro('nullify', function () { return $this->map(fn ($value) => Nullify::the($value)); }); collect(['', [], (object) [], new \stdClass, '✔']) ->nullify() ->toArray(); // [0 => null, 1 => null, 2 => null, 3 => null, 4 => '✔']
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners