Laravel api controllers – how to filter out empty ('falsy') data from database query prior to send JSON...












1















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.










share|improve this question




















  • 1





    Just a note that ->get() returns a Collection; there is no reason to call collect() on the result of a ->get(). Using ->first() returns a single Model, stdClass or null, so calling collect() on that is valid, but could also be accomplished by calling ->get() instead of ->first().

    – Tim Lewis
    Nov 21 '18 at 19:19











  • @Tim Thank you for valuable informations. As I already admit, my approach is kind of naïve. Laravel documentation is said to be very good, but I have to say that, for me, there are a lot of not-such-clear parts.

    – HynekS
    Nov 21 '18 at 19:24











  • I would say that the documentation is pretty good, but maybe not to for someone somewhat unfamiliar with PHP. And no problem, glad to help. So to clarify, by "empty", do you mean that specific columns are empty? I.e. what is a Contract? An eloquent Model referencing your contracts table? Could this be accomplished with a series of whereNotNull("column") or where("column", "!=", ""), (or false, "0" instead of "") etc etc?

    – Tim Lewis
    Nov 21 '18 at 19:28













  • @Tim: Yes, exactly, Contract is a model for contracts table. I was thinking about filtering by SQL first, by that would omit the whole row or column, wouldn't it? I need only to omit 'blank' cells.

    – HynekS
    Nov 21 '18 at 19:37






  • 1





    @Tim: These empty values are not problem per se, but they bloat up the JSON (as I wrote, probably 75–80 % of its content are property names with empty values). I also intend to cache the response somehow, and, for instance, Local Storage has quite limited size (My 'All Contracts' JSON is 3,5 Mb and it will grow with another contracts being added.)

    – HynekS
    Nov 21 '18 at 20:43
















1















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.










share|improve this question




















  • 1





    Just a note that ->get() returns a Collection; there is no reason to call collect() on the result of a ->get(). Using ->first() returns a single Model, stdClass or null, so calling collect() on that is valid, but could also be accomplished by calling ->get() instead of ->first().

    – Tim Lewis
    Nov 21 '18 at 19:19











  • @Tim Thank you for valuable informations. As I already admit, my approach is kind of naïve. Laravel documentation is said to be very good, but I have to say that, for me, there are a lot of not-such-clear parts.

    – HynekS
    Nov 21 '18 at 19:24











  • I would say that the documentation is pretty good, but maybe not to for someone somewhat unfamiliar with PHP. And no problem, glad to help. So to clarify, by "empty", do you mean that specific columns are empty? I.e. what is a Contract? An eloquent Model referencing your contracts table? Could this be accomplished with a series of whereNotNull("column") or where("column", "!=", ""), (or false, "0" instead of "") etc etc?

    – Tim Lewis
    Nov 21 '18 at 19:28













  • @Tim: Yes, exactly, Contract is a model for contracts table. I was thinking about filtering by SQL first, by that would omit the whole row or column, wouldn't it? I need only to omit 'blank' cells.

    – HynekS
    Nov 21 '18 at 19:37






  • 1





    @Tim: These empty values are not problem per se, but they bloat up the JSON (as I wrote, probably 75–80 % of its content are property names with empty values). I also intend to cache the response somehow, and, for instance, Local Storage has quite limited size (My 'All Contracts' JSON is 3,5 Mb and it will grow with another contracts being added.)

    – HynekS
    Nov 21 '18 at 20:43














1












1








1








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.










share|improve this question
















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.







php json rest laravel-5 filtering






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 19:15







HynekS

















asked Nov 21 '18 at 19:10









HynekSHynekS

4921514




4921514








  • 1





    Just a note that ->get() returns a Collection; there is no reason to call collect() on the result of a ->get(). Using ->first() returns a single Model, stdClass or null, so calling collect() on that is valid, but could also be accomplished by calling ->get() instead of ->first().

    – Tim Lewis
    Nov 21 '18 at 19:19











  • @Tim Thank you for valuable informations. As I already admit, my approach is kind of naïve. Laravel documentation is said to be very good, but I have to say that, for me, there are a lot of not-such-clear parts.

    – HynekS
    Nov 21 '18 at 19:24











  • I would say that the documentation is pretty good, but maybe not to for someone somewhat unfamiliar with PHP. And no problem, glad to help. So to clarify, by "empty", do you mean that specific columns are empty? I.e. what is a Contract? An eloquent Model referencing your contracts table? Could this be accomplished with a series of whereNotNull("column") or where("column", "!=", ""), (or false, "0" instead of "") etc etc?

    – Tim Lewis
    Nov 21 '18 at 19:28













  • @Tim: Yes, exactly, Contract is a model for contracts table. I was thinking about filtering by SQL first, by that would omit the whole row or column, wouldn't it? I need only to omit 'blank' cells.

    – HynekS
    Nov 21 '18 at 19:37






  • 1





    @Tim: These empty values are not problem per se, but they bloat up the JSON (as I wrote, probably 75–80 % of its content are property names with empty values). I also intend to cache the response somehow, and, for instance, Local Storage has quite limited size (My 'All Contracts' JSON is 3,5 Mb and it will grow with another contracts being added.)

    – HynekS
    Nov 21 '18 at 20:43














  • 1





    Just a note that ->get() returns a Collection; there is no reason to call collect() on the result of a ->get(). Using ->first() returns a single Model, stdClass or null, so calling collect() on that is valid, but could also be accomplished by calling ->get() instead of ->first().

    – Tim Lewis
    Nov 21 '18 at 19:19











  • @Tim Thank you for valuable informations. As I already admit, my approach is kind of naïve. Laravel documentation is said to be very good, but I have to say that, for me, there are a lot of not-such-clear parts.

    – HynekS
    Nov 21 '18 at 19:24











  • I would say that the documentation is pretty good, but maybe not to for someone somewhat unfamiliar with PHP. And no problem, glad to help. So to clarify, by "empty", do you mean that specific columns are empty? I.e. what is a Contract? An eloquent Model referencing your contracts table? Could this be accomplished with a series of whereNotNull("column") or where("column", "!=", ""), (or false, "0" instead of "") etc etc?

    – Tim Lewis
    Nov 21 '18 at 19:28













  • @Tim: Yes, exactly, Contract is a model for contracts table. I was thinking about filtering by SQL first, by that would omit the whole row or column, wouldn't it? I need only to omit 'blank' cells.

    – HynekS
    Nov 21 '18 at 19:37






  • 1





    @Tim: These empty values are not problem per se, but they bloat up the JSON (as I wrote, probably 75–80 % of its content are property names with empty values). I also intend to cache the response somehow, and, for instance, Local Storage has quite limited size (My 'All Contracts' JSON is 3,5 Mb and it will grow with another contracts being added.)

    – HynekS
    Nov 21 '18 at 20:43








1




1





Just a note that ->get() returns a Collection; there is no reason to call collect() on the result of a ->get(). Using ->first() returns a single Model, stdClass or null, so calling collect() on that is valid, but could also be accomplished by calling ->get() instead of ->first().

– Tim Lewis
Nov 21 '18 at 19:19





Just a note that ->get() returns a Collection; there is no reason to call collect() on the result of a ->get(). Using ->first() returns a single Model, stdClass or null, so calling collect() on that is valid, but could also be accomplished by calling ->get() instead of ->first().

– Tim Lewis
Nov 21 '18 at 19:19













@Tim Thank you for valuable informations. As I already admit, my approach is kind of naïve. Laravel documentation is said to be very good, but I have to say that, for me, there are a lot of not-such-clear parts.

– HynekS
Nov 21 '18 at 19:24





@Tim Thank you for valuable informations. As I already admit, my approach is kind of naïve. Laravel documentation is said to be very good, but I have to say that, for me, there are a lot of not-such-clear parts.

– HynekS
Nov 21 '18 at 19:24













I would say that the documentation is pretty good, but maybe not to for someone somewhat unfamiliar with PHP. And no problem, glad to help. So to clarify, by "empty", do you mean that specific columns are empty? I.e. what is a Contract? An eloquent Model referencing your contracts table? Could this be accomplished with a series of whereNotNull("column") or where("column", "!=", ""), (or false, "0" instead of "") etc etc?

– Tim Lewis
Nov 21 '18 at 19:28







I would say that the documentation is pretty good, but maybe not to for someone somewhat unfamiliar with PHP. And no problem, glad to help. So to clarify, by "empty", do you mean that specific columns are empty? I.e. what is a Contract? An eloquent Model referencing your contracts table? Could this be accomplished with a series of whereNotNull("column") or where("column", "!=", ""), (or false, "0" instead of "") etc etc?

– Tim Lewis
Nov 21 '18 at 19:28















@Tim: Yes, exactly, Contract is a model for contracts table. I was thinking about filtering by SQL first, by that would omit the whole row or column, wouldn't it? I need only to omit 'blank' cells.

– HynekS
Nov 21 '18 at 19:37





@Tim: Yes, exactly, Contract is a model for contracts table. I was thinking about filtering by SQL first, by that would omit the whole row or column, wouldn't it? I need only to omit 'blank' cells.

– HynekS
Nov 21 '18 at 19:37




1




1





@Tim: These empty values are not problem per se, but they bloat up the JSON (as I wrote, probably 75–80 % of its content are property names with empty values). I also intend to cache the response somehow, and, for instance, Local Storage has quite limited size (My 'All Contracts' JSON is 3,5 Mb and it will grow with another contracts being added.)

– HynekS
Nov 21 '18 at 20:43





@Tim: These empty values are not problem per se, but they bloat up the JSON (as I wrote, probably 75–80 % of its content are property names with empty values). I also intend to cache the response somehow, and, for instance, Local Storage has quite limited size (My 'All Contracts' JSON is 3,5 Mb and it will grow with another contracts being added.)

– HynekS
Nov 21 '18 at 20:43












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419026%2flaravel-api-controllers-how-to-filter-out-empty-falsy-data-from-database-q%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419026%2flaravel-api-controllers-how-to-filter-out-empty-falsy-data-from-database-q%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

'app-layout' is not a known element: how to share Component with different Modules

android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

WPF add header to Image with URL pettitions [duplicate]