Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fbc's avatar
Level 2

How do I get a count of how many columns are (or aren't) null in a query?

Basically I have a survey with 30 questions that creates a record in a database. Sometimes people forget they only answered 25% of the survey questions.

How do I get a count of how many columns where left 'null' in a query?

0 likes
10 replies
Drfraker's avatar

$query->whereNull('column_name')->count();

fbc's avatar
Level 2

@DRFRAKER - I want to count the empty columns in the returned row. My query will always return one row.

fbc's avatar
Level 2

@DRFRAKER - For example: How many profile questions has the user not filled out.

I'm looking for something like: {{ $user->profile->count(empty columns) }}

fbc's avatar
Level 2

@DRFRAKER - I'm using Linux. So installing microsoft assets might be a problem. Thanks though.

shez1983's avatar
$entity =  Model::find(1); 

if ( count($entity->attributes) !==  array_filter($entity->attributes)) {
   echo 'profile incomplete'
}

you could also use array_unique... and there might be a collection method for doing the same..

Cronix's avatar
Cronix
Best Answer
Level 67

Since you're wanting the count on the model of unanswered questions, you could just create an accessor on the model which returns the filtered count. Then you could easily just show them how many questions, or percentage of questions, they haven't answered yet (like a progress bar).

https://laravel.com/docs/5.7/eloquent-mutators#accessors-and-mutators

Haven't tested it, but something like

public function getUnansweredQuestionCountAttribute() {
    return count(array_filter($this->attributes));
}
$questions = QuestionModel::someQuery();

echo $questions->unanswered_question_count
1 like
fbc's avatar
Level 2

@CRONIX - Wow, that is exactly where I was going with it. Thanks!!!

sanjayacloud's avatar

@cronix

I am doing the same thing.

I add this below method in my question model.

public function getUnansweredQuestionCountAttribute() {
    return count(array_filter($this->attributes));
}

and I access it like below.

 $qs = Question::where('user_id', Auth::user()->id)->count();
            dd($qs->getUnansweredQuestionCountAttribute);

I got App\Question::getUnansweredQuestionCountAttribute must return a relationship instance.

Any idea?

Please or to participate in this conversation.