This also can be used to count limited query:
function getLimitedQueryCount($query) {
$limit = $query->getQuery()->limit;
$count = $query->count();
return $limit ? min($limit, $count) : $count;
}
// Usage
$queryToCount = UsersModel::where('age', '>=', 18)->latest()->limit(10);
$count = getLimitedQueryCount($queryToCount);
Basically, we are using query instance's limit property and then compare it with actual query count and use the minimum value. If there's no limit, we're using the regular query count.
Sources:
https://laravel.com/api/11.x/Illuminate/Database/Eloquent/Builder.html#method_getQuery https://laravel.com/api/11.x/Illuminate/Database/Query/Builder.html