[SOLVED] How to order posts by like date?
liorocks opened this issue · 1 comments
liorocks commented
I need to order posts by DESC of when the user has liked them.
I've got the following code:
Post::whereLiked($userId)->paginate();
I tried something like this, but got me nowhere.
Post::whereHas('likes', function($q) use($userId) {
return $q->where('user_id', $userId)->orderBy('created_at', 'DESC');
})->paginate();
What i'm doing wrong here?
liorocks commented
Ok, I've managed to do this by myself.
I've added this method to the Post model:
public static function getLikes($user_id) {
return (new static)
->join('likeable_likes', 'posts.id', '=', 'likeable_likes.likable_id')
->select('posts.*')
->where('likeable_likes.user_id', '=', $user_id)
->orderBy('likeable_likes.created_at', 'DESC');
}
And the usage is:
Post::getLikes($user_id)->get();
If someone has a better solution, please post it.