Answer the question
In order to leave comments, you need to log in
How to sort user posts by creation date?
Good afternoon. I select posts of one user by his id. It sorts them in the same order as in the database. And I need to sort by created_at so that the latest ones are first. I tried orderBy('created_at', 'desc'), it says that there is no such method. Nothing swears at the sortBy('created_at') and sortByDesc('created_at') methods, so they don't change anything either. How to do it? The method where this is done is something like this:
public function getPostsById($id)
{
$model = Post::findOrFail($id);
$response = $model->posts;
return response()->json($response);
}
Answer the question
In order to leave comments, you need to log in
You need to get the posts of one user
$user = User::find($id);
$posts = $user->posts; // Если есть связь от одного пользователя.
return response()->json($posts->sortByDesc('created_at')); // и вызвать сортировку коллекции.
$posts = Post::where('user_id', '=', $user_id)
->orderBy('created_at', 'desc')
->get();
return response()->json($posts);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question