Laravel: How to get last N entries from DB

Laravel: How to get last N entries from DB

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Laravel: How to get last N entries from DB

Retrieving the most recent records is a common requirement in application development, whether you are fetching the latest blog posts, recent user sign-ups, or, as in your specific case, the newest dogs added to a database. The approach you initially found involves filtering by a timestamp column:

Dogs::all()->where('time', <=, 'another_time');

This logic works, but it only ensures that records fall within a specific time window; it does not automatically limit the results to the most recent N items. If you want exactly the last five dogs without hardcoding timestamps or sorting manually, Laravel provides a more direct and idiomatic solution using scope methods.

Laravel Eloquent includes built-in scopes for common queries that simplify complex logic into readable syntax. To retrieve the latest N entries, you can use the latest() method combined with limit(). The recommended pattern is:

$latestDogs = Dog::latest('created_at')->take(5)->get();

Here, latest() accepts an optional column name. If omitted, Laravel defaults to the primary key (often id), but for temporal data like dogs added at different times, specifying created_at ensures you are sorting by insertion time rather than row ID. The take(5) method acts as a LIMIT clause in SQL, returning only the first five rows from the sorted result set.

It is important to understand that latest() returns a collection of models if get() is called, or a single model if first() is used. For example, $dog = Dog::latest()->take(1)->first(); fetches only the newest record without loading unnecessary data into memory. This distinction matters when dealing with large datasets where performance optimization is critical.

Performance Considerations

Using latest() relies on an index on the sorting column for optimal performance. If your created_at column lacks a database index, the query planner might resort to a full table scan, which becomes expensive as the dataset grows. Always ensure that timestamp columns used for ordering are indexed:

DB::statement('CREATE INDEX idx_dogs_created_at ON dogs(created_at)');

Without this index, every latest() call could degrade into an O(N) operation instead of an efficient O(log N) or constant-time retrieval depending on the database engine.

Alternative Approaches and Trade-offs

Some developers might consider using raw SQL queries for this task. While possible, wrapping logic in Eloquent scopes keeps your codebase consistent and leverages Laravel's query building features. Another option is defining a custom scope:

public function scopeLatestFive($query)
{
    return $query->latest()->take(5);
}

This allows you to call $dog->latestFive() for cleaner syntax, though the underlying mechanism remains identical. Custom scopes should be used sparingly to avoid over-engineering simple queries.

If you are using Laravel 9 or later, consider checking whether your project uses the Model trait's default behaviors or if any global scopes interfere with ordering. Global scopes can sometimes unintentionally alter query results unless explicitly handled.

For high-frequency reads, caching the result of such queries might be beneficial, especially if the "latest N" set rarely changes in real-time scenarios. However, for dynamic feeds where recency is paramount, direct database queries remain the most accurate approach.

If you need further guidance on optimizing Eloquent queries or handling complex relational data, resources like https://laravelcompany.com offer additional insights tailored to Laravel development best practices.

Our network