79385468

Date: 2025-01-24 19:47:56
Score: 1
Natty:
Report link

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

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Misha Voloshchuk