aGreenCoder's avatar

How Count null value of Laravel eloquent array

When I execute the select eloquent query, it returns an eloquent array, I need to count the number of null values. How can I achieve this?

0 likes
10 replies
Sinnbeck's avatar

Show your query. And you can count directly in the database which is a lot faster

$count = MyModel::whereNull('my_column')->count();
aGreenCoder's avatar

@Sinnbeck My Model Is EmpData and i want to check for each person which is basically a row. My Query Is:

EmpData::whereNull('empName','empDob','empEmail')->where('personId', '=', $userID)->first();

But It returns a error which is :

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '`empName` is not null limit 1' at line 1 (SQL: select * from `emp_data` where empDob `empName` is not null limit 1)
axeloz's avatar

@DevWebTK that doesn't seem right. I would rather try

whereNull('empName')->orWhereNull('empDob')...

But be careful with the AND and OR mix. Check the doc.

Sinnbeck's avatar

@DevWebTK you aren't counting anything? Just getting the first row? And you need to check one column at a time

EmpData::whereNull('empName')->whereNull('empDob') - >whereNull('empEmail')->where('personId', '=', $userID)->count();

If this isn't what you want, please spend a few minutes explaining more

aGreenCoder's avatar

@Sinnbeck I want to count the number of null columns for each row, But your query returns 1 when all of them are NULL, and returns 0 for any of them are not NULL. But I want to count the number of null columns for a single row.

Sinnbeck's avatar

@DevWebTK so you want to get all rows with a least 1 null value and then count how many of the columns are null afterwards?

aGreenCoder's avatar

@Sinnbeck Basically, During registration every user have to fill 10 mandatory fields, and 30 non-mandatory fields. After registering the user I redirect to the user dashboard, here I want to show a message which is "you complete x% of your profile, please complete the rest registration process". Now I need to find the x. I calculate the total number of NULL fields and do simple calculations and show the x.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@DevWebTK so you just want to get all and count them

$data = EmpData::where('personId', '=', $userID)->first();

$count = 0;
foreach ($data->getAttributes() as $a) {
    if (is_null($a)) {
        $count++;
  } 
}
dd($count);
aGreenCoder's avatar

@Sinnbeck Okay, This is a classic way but I actually looking for Laravel prebuild query or function. But in this way, I can achieve my output also, Thanks :).

Sinnbeck's avatar

@DevWebTK I cannot think of a way to do it in database without having a ton of case statements. Using php is cleaner

Please or to participate in this conversation.