Search code examples
phplaravellaravel-5lumenlaravel-6

Get total of Collection


How can I get a total of records after I used skip and take from a query?

Codes Working:

$records = Model::where('active', 1)
                 ->skip(($page -1 ) * $max)
                 ->take($max);
// List of records
$data = $records->get()

//Total of all records including the skip records
$total = $records->paginate()->total();

I want this way but Codes Not Working:

$records = Model::where('active', 1)
                 ->skip(($page -1 ) * $max)
                 ->take($max)->get();

//Not Working 
$total = $records->paginate()->total();

//Not Working 
$total = $records->total();

//Not Working wrong result
$total = $records->count();

How can I get the all total records in the collection?


Solution

  • Use the paginate() method directly on your model:

    $records = Model::where('active', 1)->paginate($recordsPerPage);
    

    That will return a LengthAwarePaginator instance, which has a lot of useful methods:

    https://laravel.com/api/7.x/Illuminate/Contracts/Pagination/LengthAwarePaginator.html

    Such as $records->total(), $records->perPage(), etc.