Laravel orderBy Relationship via Eager Loading method
For example, imagine having a Post model and you want to order the relationship Comment by its "ID" column in "descending" order. To write that you can write your code as follows. The "with()" method can accept a function that can receive the query of the "relationship" so from there you can write your necessary condition. Besides using "with()" method you can also use the "load" method if you already have the Eloquent Model instance.
<?php $sortDirection = 'desc'; // 1: Using "with" method Post::query()->with(['comments' => function ($query) use ($sortDirection) { $query->orderBy('id', $sortDirection); }]); // 2: Using "load" method $post = Post::first(); $post->load(['comments' => function ($query) use ($sortDirection) { $query->orderBy('id', $sortDirection); }]);
Laravel orderBy Condition on Model Relationship
Another way to order the relationship is like below, you can define the relationship such as "hasMany()" and then later chain it with the "orderBy()" method.
<?php // app\Models\Post.php public function comments() { return $this->hasMany(Comment::class)->orderBy('column'); }
Leave a reply