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!

Like our articles?
Check out our Laravel online courses!

6 COMMENTS

  1. public function products($order = ‘name’)
    {
    return $this->hasMany(‘App\Product’)->orderBy(‘id’,’desc’);
    }

    • Of course you can do that but what if I want the unordered simple list, This can be better done this way:

      public function products($order = NULL, $key = NULL)
      {
      if($order && $key){
      return $this->hasMany(‘App\Product’)->orderBy($key, $order);
      }

      return $this->hasMany(‘App\Product’);
      }

      Now you can get products like this:

      For ordered products:
      ->products(‘desc’, ‘id’)

      For unordered products:
      ->products()

      • This is the more flexible and correct way of doing it.
        The only thing I’d add is when retrieving the products with a custom order, include ->get()

        so:
        ->products(‘desc’, ‘id’)->get();

LEAVE A REPLY

Please enter your comment!
Please enter your name here