I
I
Ivan2020-08-17 13:44:57
Laravel
Ivan, 2020-08-17 13:44:57

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

2 answer(s)
A
Anton October, 2020-08-17
@Djonson86

You need to get the posts of one user

$user = User::find($id);
$posts = $user->posts; // Если есть связь от одного пользователя.

return response()->json($posts->sortByDesc('created_at')); // и вызвать сортировку коллекции.

Plus, you need to understand the differences:
1) orderBy is sorting in QueryBuilder, roughly speaking in SQL Read here . Therefore, in your case, it wrote that there is no such method because the collection called it.
as an option with orderBy
$posts = Post::where('user_id', '=', $user_id)
->orderBy('created_at', 'desc')
->get();

return response()->json($posts);

2) And sortBy / sortByDesc sort the finished collection Read here (example above).

J
jazzus, 2020-08-17
@jazzus

$user->posts - collection
$user->posts() - query
query with sorting:

$user->posts()
     ->latest()
     ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question