Home > Mobile >  Laravel pagination and model count returns duplicated query
Laravel pagination and model count returns duplicated query

Time:07-05

Hello is there a way to count model count results without duplicating the query?

I am getting all users (with pagination) and at the top of the page, I want to count the User model and display how many users I have in total. The debugbar returns that I have duplicated the count(*) query and it does not make any problems but I'd like to know if there is a way to get both results without duplicating the query.

IMG OF QUERIES:

enter image description here

These are the functions that are "causing the issue":

public static function getUsers() {
    return User::withoutTrashed()->select(['id', 'name', 'email', 'status', 'isAdmin', 'isMember'])->paginate(15);
}

public static function getUsersCount() {
    return User::count();
}

And here is the provided data for the view:

$users = User::getUsers();
    $usersCount = User::getUsersCount();
    return view('dashboard.users.index', [
        'users' => $users,
        'usersCount' => $usersCount
    ]);

CodePudding user response:

To get the total items returned call:

$paginator->total()

This needs to be one a LengthAwarePaginator: https://laravel.com/docs/9.x/pagination#paginator-instance-methods

  • Related