Navigation

Laravel

How to Use `latest()` and `oldest()` to Order Queries

Simplify date-based ordering in Laravel with latest() and oldest() methods. A cleaner alternative to orderBy() for timestamp columns.

Problem: You frequently need to order records by creation date, but writing orderBy('created_at', 'desc') repeatedly is verbose.

Solution:

// Get newest records first (descending order)
$recentPosts = Post::latest()->get();

// Get oldest records first (ascending order)
$oldestUsers = User::oldest()->get();

// Use with a different date column
$recentlyUpdated = Product::latest('updated_at')->get();
$firstPublished = Article::oldest('published_at')->get();

// Combine with other query constraints
$recentActiveUsers = User::where('status', 'active')
    ->latest()
    ->take(10)
    ->get();

// Works with paginate
$posts = Post::published()
    ->latest()
    ->paginate(15);

Why it works: latest() is shorthand for orderBy('created_at', 'desc') and oldest() for orderBy('created_at', 'asc'). Pass a column name to order by a different timestamp field. These methods make queries more readable and are chainable with other query builder methods.

Note: Both methods default to the created_at column. If your table doesn't have this column and you don't specify one, you'll get a SQL error.

Table Of Contents

Related Topics

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel