Created
July 7, 2019 18:56
-
-
Save rakeshsoni18/e13862ad0ca5fd2bdddb94a9bf09edc1 to your computer and use it in GitHub Desktop.
Eloquent Relationships – with “automatic” orderBy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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