In this episode, we tackle a common issue when working with Eloquent in Laravel: what to do when you've already set an order on a relationship (like latest()
in a model) but later need to change the order, say for changing sort direction with a URL parameter.
We start by looking at a simple discussion-posts setup where posts are displayed in a certain default order. By adding latest()
to the posts relationship, we sort by newest posts first. But what if the user wants to see the oldest post first? At first, it might seem like you can just call oldest()
in the controller, but you quickly discover that doesn't override the previous ordering—Laravel keeps using the one you set in the relationship.
To solve this, we introduce Laravel's reorder()
method on the query builder. We go through how reorder()
works: you can call it with no arguments to wipe out existing order, letting you then chain a new orderBy()
, or you can pass your own column and direction straight into it. We show both methods in action, so you can pick the approach that best fits your use case.
By the end of the video, you'll know exactly how to override default ordering on your Eloquent relationships and avoid getting stuck with a sort you didn't want!