Spent a good amount of time trying to return all Users that match a custom field value.

Reading the docs here, it shows a findAll() command.

However, when trying the code below, it's not working.

use craft\elements\User;

$value = 'some string';

$users = User::findAll(['customField' => $value]);

return count($users);  

The query doesn't fail, but rather, it times out. If I put in a non-valid custom field, an error is thrown.

Any ideas how to get a count of all Users that match a custom field value?

EDIT: This actually does work as expected! My code included a do/while loop, which was the issue. Leaving the questions up in case someone else is searching for this or has a different solution.

1 Answer 1


While this does work, the User::findAll() method is just a wrapper around the User::find() method, which creates a UserQuery. I would prefer using a UserQuery directly, since you get more autocompletion and type-safety compared to criteria arrays. Another issue is using count() on the query directly, without executing it first. This is less efficient, since the query is executed behind the scenes, and a potential source of bugs and confusion.

A more idiomatic way to write your query would be this:

use craft\elements\User;

return User::find()
    ->customField('some string')

By executing the query with count(), the database only returns the count, not all the data for all the users. This is more efficient if you don't need the actual users.

If you need the user objects as well, I would execute the query first and then count the resulting array:

$users = User::find()
    ->customField('some string')
$count = count($users);
  • Great, thanks for the tip! Commented Jan 11 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.