Home > Mobile >  Find out if records exists after limit
Find out if records exists after limit

Time:01-30

So I am wondering is there any other way to know if any record exists after limit?

For example, I only need to fetch 20 results, but I also need to know if there is more records left after that limit so that I could add one more page for my pagination:

User::query()->limit(21)->get();

This is what I am doing now, but I don't like it because I am fetching one extra result to know if it has more records.

Would appreciate any possible solutions.

I am not using simplePaginate method. But as I know simplePaginate says if more records exists to display other page.

CodePudding user response:

Try paginate() instead of limit

CodePudding user response:

To get the total number of collections on your table, you can get the total by:

$totalUser = User::count();

Suppose, this returns 500. That mean's you have currently 500 Users.

And then you need to take first 20 rows. Then you can write code like:

$users = User::query()->limit(20)->get();

The second one will get the 20 rows. Then if you write a condition like this:

if($totalUser > $users->count()) {
    // Write code here considering have more data on your users table
}

CodePudding user response:

try counting before you fetch as @cerlin suggested, like so

$count_of_all_records = User::all()->count;

// or you can fetch your 20 records but also check if the next exists on the fly
$more_is_left = User->where('id', 1)->exists();

if you are not using pagination.

  •  Tags:  
  • Related