how do you exclude null values from an array of objects in a laravel form request validation?

You can filter whenever you have a null value, then filter again if the array is now empty. There are multiple ways to achieve this, this is only a possible solution.

<?php

$validated = json_decode('{
"name":"Some Name",
"details":{
          "subscriptions":["1"],
          "size":[null,null],
          "notes":["10 pcs",null],
          "price":[100,null]}
}', true);

//filter null values
foreach($validated['details'] as $key => $detail) {
    $validated['details'][$key] = array_filter($validated['details'][$key], function ($value) {
        return !is_null($value);
    });
}

//filter empty arrays
$validated['details'] = array_filter($validated['details'], function ($value) {
   return !empty($value);
});

print_r($validated);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top