Reputation: 801
When having a Eloquent relation, you get the relation like:
$page->photos->toArray();
.
But I want the relation ordered. How?
$page->photos->orderBy('order')->toArray();
does now work: Call to undefined method Illuminate\Database\Eloquent\Collection::orderBy()
Upvotes: 1
Views: 175
Reputation: 50561
You can use the returned relation as a builder object from your relation method.
$page->photos()->orderBy('order')->get();
$page->photos()
returns a relation type object and $page->photos
is the dynamic property that loads the relationship and returns the result. In this case an Eloquent\Collection
.
Docs - Eloquent - Dynamic Properties
You can also order this relationship while eager loading if needed.
Eager Loading Constraints (there is an example that uses orderBy in the docs)
Upvotes: 3
Reputation: 153150
By calling the method of the relation you get the relation object on which you can run further queries. Now you're using the dynamic property which get's you the result of the relation.
$page->photos()->orderBy('order')->get()->toArray();
Upvotes: 3