mitt
mitt

Reputation: 3

I need to get the 5 posts with the most likes

I'm currently making a news system, and I need to get the top 5 posts with the most likes. Below my code and tables:

Models:

Post:

class Post extends Model
{
    use HasFactory;
    use HasTags;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function likes()
    {
        return $this->hasMany(PostLike::class);
    }

    public function comments()
    {
        return $this->hasMany(PostComment::class);
    }
}

Likes:

class PostLike extends Model
{
    protected $fillable = ['user_id', 'post_id', 'is_liked'];
    
    public function user(){
       return $this->belongsTo(User::class); 
    }
    public function post(){
        return $this->belongsTo(Post::class);
    }
    use HasFactory;
}

Tables:

posts: posts table

post_likes: post likes table

Upvotes: 0

Views: 457

Answers (1)

Michael Mano
Michael Mano

Reputation: 3440

No idea why you have a is_liked bool since if the relation exists, its liked. but this should work

Post::withCount('likes')->orderBy('likes_count', 'desc')->take(5)->get();

Upvotes: 3

Related Questions