When retrieving a set of related models, it's often useful to order them in a specific way. In Laravel, this can be achieved using the orderBy method.
Consider the following scenario where you're looping through all comments posted by the Author of a particular post:
foreach($post->user->comments as $comment) { echo "<li>" . $comment->title . " (" . $comment->post->id . ")</li>"; }
This code will display the following list of comments:
I love this post (3) This is a comment (5) This is the second Comment (3)
To order the comments by post ID, extend the hasMany relationship in the User model:
public function comments() { return $this->hasMany('Comment')->orderBy('column'); }
Replace column with the name of the column you want to order by. In this case, we'll use id:
public function comments() { return $this->hasMany('Comment')->orderBy('id'); }
This will update the order of the comments to be:
I love this post (3) This is the second Comment (3) This is a comment (5)
In addition to hard-coding the order in the relationship, you can also order based on a query parameter. To do this, define a route in your routes.php file:
Route::get('users/{user}/comments', 'UserController@index');
And then create a corresponding index method in your UserController:
public function index($user) { $column = Input::get('orderBy', 'defaultColumn'); $comments = $user->comments()->orderBy($column)->get(); // ... }
When you visit the route with a orderBy parameter, the comments will be ordered accordingly. For example, visiting the following URL would order the comments by the created_at column:
http://localhost/users/1/comments?orderBy=created_at
The above is the detailed content of How to Order Related Models in Laravel Using `orderBy`?. For more information, please follow other related articles on the PHP Chinese website!