Laravel Query Builder: Get Records with OFFSET and LIMIT

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Laravel’s Eloquent ORM is widely celebrated for its ability to handle complex database operations with minimal fuss. However, there are times when developers may need or prefer to use the underlying query builder for more fine-grained control or perform raw SQL-like queries. One common use case is paginating results, which requires understanding how to leverage ‘OFFSET’ and ‘LIMIT’ within Laravel’s query builder. In this tutorial, we’ll explore various methods to implement pagination using ‘OFFSET’ and ‘LIMIT’ in Laravel’s query builder.

Understanding OFFSET and LIMIT

‘LIMIT’ and ‘OFFSET’ are SQL clauses that control the number of records returned by a query and where to start returning records from, respectively. ‘LIMIT’ specifies the maximum number of records to return, while ‘OFFSET’ indicates the number of records to skip before starting to return records. This is particularly useful for implementing features like pagination.

Basic OFFSET and LIMIT with get()

$users = DB::table('users')
    ->offset(10)
    ->limit(5)
    ->get();

This code snippet retrieves a chunk of 5 users, skipping the first 10 users in the database. The ‘get()’ method executes the query and returns the result set.

Using OFFSET and LIMIT with paginate()

$users = DB::table('users')->paginate(15);

Laravel also provides a convenient ‘paginate()’ method which abstracts the complexity of ‘LIMIT’ and ‘OFFSET’ into a simple, fluent interface. It also handles generating pagination links. The code above will paginate the users, fifteen per page.

OFFSET and LIMIT with Joins

$posts = DB::table('posts')
    ->join('users', 'users.id', '=', 'posts.user_id')
    ->offset(5)
    ->limit(10)
    ->get(['posts.*', 'users.name as user_name']);

When working with ‘joins’, ‘OFFSET’ and ‘LIMIT’ work similarly. The above query joins the ‘posts’ table with the ‘users’ table to also retrieve the name of the author, then limits the result set to 10 posts after skipping the first five.

Advanced OFFSET and LIMIT Scenarios

The Laravel query builder supports advanced scenarios where you might want to apply ‘OFFSET’ and ‘LIMIT’ alongside other clauses like ‘where’, ‘orderBy’, etc. This allows for a high degree of customization.

For example, you could filter the records further:

$users = DB::table('users')
    ->where('active', 1)
    ->orderBy('name', 'asc')
    ->offset(10)
    ->limit(5)
    ->get();

This would get 5 ‘active’ users, starting from the eleventh ‘active’ user as per the alphabetical order of their name.

OFFSET and LIMIT for Batch Processing

In scenarios involving batch processing of records, ‘OFFSET’ and ‘LIMIT’ become particularly important. For example, if you are sending emails to your users in batches:

$users = DB::table('users')
    ->offset(0)
    ->limit(50)
    ->get();

do {
    // Process each user
    foreach ($users as $user) {
        // Send email...
    }
    // Get the next batch
    $offset += 50;
    $users = DB::table('users')
        ->offset($offset)
        ->limit(50)
        ->get();
} while (! $users->isEmpty());

This loop continues to fetch and process users in batches of 50 until there are no more users to process.

Conclusion

In conclusion, ‘OFFSET’ and ‘LIMIT’ are powerful tools for controlling the flow of data from your database. Laravel’s query builder provides a fluent, convenient interface for working with these SQL clauses and helps streamline tasks like pagination and batch processing. By incorporating these features into your application, you’ll gain fine-grained control over data retrieval to build scalable and efficient features.