Home  >  Article  >  Database  >  How to Limit Query Results and Implement Pagination in Laravel using Eloquent?

How to Limit Query Results and Implement Pagination in Laravel using Eloquent?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 06:29:03178browse

How to Limit Query Results and Implement Pagination in Laravel using Eloquent?

Pagination in Laravel using Eloquent ORM

Eloquant ORM, Laravel's object-relational mapper, provides convenient methods for interacting with the database. One common task is to limit the number of results returned from a query.

Problem: How can you emulate the following SQL query using Eloquent's ORM?

<code class="sql">SELECT * FROM `games` LIMIT 30, 30;</code>

Solution:

Create a Game model that extends Eloquent and use the following code:

<code class="php">Game::take(30)->skip(30)->get();</code>

Here, take() retrieves a specified number of records (30 in this case), and skip() offsets the result to a specified number of records (also 30).

Alternative syntax (Laravel 8 and above):

In newer versions of Laravel, you can use the more intuitive:

<code class="php">Game::limit(30)->offset(30)->get();</code>

The above is the detailed content of How to Limit Query Results and Implement Pagination in Laravel using Eloquent?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn