I am using Laravel REST API endpoints to fetch data from a MySQL database. A significant number of cells (let's say 80–90 %) are 'blank' or 'falsy', by which I mean null
, empty string, false
or 0
. I struggle to find a way to filter these data out to save bandwidth (and the overall volume of JSON response).
As I found out from docs and similar questions on this site, I should go for Laravel's collection
wrapper and its filter()
method. It works perfectly when applied to single row query, like that:
public function getByNumberOfYear($year, $num)
{
$contractNumOfYear = Contract::NumberOfYear($year, $num)->first();
$collection = collect($contractNumOfYear);
return $collection->filter();
}
But it does't work if naïvely applied on query containing multiple rows (= array of objects in JSON response):
public function showYear($year)
{
$contractFromYear = Contract::year($year)->get();
$collection = collect($contractFromYear);
return $collection->filter();
}
It doesn't throw an error, but in the resulting array of objects (in JSON) the falsy data persists. What am I missing? I'm mostly a front-end guy and I don't know PHP much. Do I have to loop through the query and then apply filter? Any help would be much appreciated.