nhusby said:
I've been using Eloquent in a project outside of Laravel, and I needed pagination, so I built my own pager. I discovered that Eloquent doesn't really have a good solution to get the total rows found, especially when using eager loading, so I made this function.
I put a significant amount of effort into this, and I thought it might be of use to someone.
public static function calc_eloquent_found( $query_builder ){ $query = clone $query_builder->getQuery();
$query->selectRaw('COUNT( DISTINCT '. $query_builder->getModel()->getKeyName() .' ) as total'); $query->limit = null; $query->offset = null; //TODO: this needs more testing. if( $query->groups ){ $subquery = $query->toSql(); $chunks = explode( '?', $subquery ); $bindings = $query->getBindings(); // do I need to strip out potential select bindings? $arr = []; foreach( $chunks as $i => $chunk ){ $arr[] = $chunk; if( $bindings[ $i ] ){ if( is_string( $bindings[ $i ] ) && !is_numeric( $bindings[ $i ] ) ){ $bindings[ $i ] = '"'. $bindings[ $i ] . '"'; } $arr[] = $bindings[ $i ]; } } $subquery = implode( '', $arr ); $result = DB::select( DB::raw("SELECT SUM( sub.total) AS total FROM ($subquery) AS sub") )[0]['total']; return $result; } return $query->pluck('total');
}
Hi mate, thank you for your suggestion. Can you please let me know where did you added this function? Is it an eloquent class you extended ? If yes then which one?
Thank you.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community