Eloquent Relationships - with "automatic" orderBy

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!

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by

You might also like