Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rakeshsoni18/e13862ad0ca5fd2bdddb94a9bf09edc1 to your computer and use it in GitHub Desktop.

Select an option

Save rakeshsoni18/e13862ad0ca5fd2bdddb94a9bf09edc1 to your computer and use it in GitHub Desktop.
Eloquent Relationships – with “automatic” orderBy
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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment