Support the ongoing development of →
Database Eloquent
Last updated 2 years ago.

Could you be so kind and show how do you use it in example. Thanks.


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( 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!


Your banner here too?

nhusby nhusby Joined 5 May 2014


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 - All rights reserved.