Replace verbose orderBy('created_at', 'desc') clauses with the clean latest() and oldest() query builder helpers.
Sorting records by creation timestamp is the most common ordering operation in database queries.
Instead of writing orderBy('created_at', 'desc') or orderBy('created_at', 'asc'), Laravel provides the latest() and oldest() query builder methods.
Basic Usage
use App\Models\Post;
// Equivalent to: orderBy('created_at', 'desc')
$newestPosts = Post::latest()->paginate(15);
// Equivalent to: orderBy('created_at', 'asc')
$oldestPosts = Post::oldest()->paginate(15);
Ordering by Custom Date Columns
Pass a column name to sort chronologically by custom date or integer columns:
// Sort by published_at DESC
$recentArticles = Article::latest('published_at')->get();
// Sort by scheduled_for ASC
$upcomingEvents = Event::oldest('scheduled_for')->get();
Summary
- Defaults to the model's
created_attimestamp column. - Accepts custom column names as the first argument.
- Clean and self-documenting builder syntax.
Related Tips
View all tips →Scope Pivot Table Queries with Closures in wherePivot() in Laravel 13.26
Laravel 13.26 allows wherePivot() and orWherePivot() to accept closures, enabling direct reuse of local scopes defined on custom Pivot models.
Execute Custom Fallbacks on Missing Records with firstOr()
Use firstOr() to retrieve the first matching database record or execute a custom fallback closure when no record is found.