Skip to main content
Tutorial Free

Eloquent Relationships - with "automatic" orderBy

September 30, 2015
1 min read
Quick tip for today - let's imagine we have a one-to-many relationship between Categories and Products, and we often show list of products here and there in our app. What if we want them ordered by name alphabetically? Should we add orderBy in every query? No, we can define that in relationship itself. Our usual Eloquent relationship looks something like this:
class Category extends Model
{
    public function products()
    {
        return $this->hasMany('App\Product');
    }
}
So here's what we should do to automatically order products by title in every query that uses this relationship:
    public function products()
    {
        return $this->hasMany('App\Product')->orderBy('name');
    }
That's it, everything is "in order" now!

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses on Laravel Daily

No comments yet…