user1469734
user1469734

Reputation: 801

Laravel Eloquent order Relation

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

Answers (2)

lagbox
lagbox

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

lukasgeiter
lukasgeiter

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

Related Questions