How to get the filtered record count for a query?

I am using codeigniter 4 model for a an application which I work. I would like to get the filtered record count for a query as shown.

My code is a shown below:

$model = new LocationModel();
$builder = $model->builder();

if($filterName != "" && $filterValue != "") {
$builder->where($filterName, $filterValue);
}

$data = [];
$data['locations'] = $model->findAll();
$data['recordCount'] = $model->countAllResults();

I tried countAllResults as shown in my code above and it gives the count of full records available in table.

Can you please suggest a way to get the count fetched in the findAll?

Please note that I want the results fetched in the above query(not the record count in the database table).

You’re calling findAll() on the model, which ignores the query builder filters you’ve applied — that’s why you’re getting all records instead of the filtered count.

Straight answer:

To get the filtered count, use the same $builder you applied the filter to, and call:

$builder->countAllResults(false);

The false argument tells it not to reset the query, so you can reuse the same builder if needed.


Corrected code:

$model = new LocationModel();
$builder = $model->builder();

if ($filterName !== "" && $filterValue !== "") {
    $builder->where($filterName, $filterValue);
}

$data = [];
$data['recordCount'] = $builder->countAllResults(false); // Get filtered count
$data['locations'] = $builder->get()->getResult();       // Get filtered data

Summary:

  • findAll() ignores any manual filters applied to $builder
  • Use $builder->get() to fetch filtered results
  • Use $builder->countAllResults(false) for filtered record count

Let me know if you’re paginating or need search/filtering across multiple fields.