0

I am using Laravel 7.26 and I have two tables, categories and posts they share the following relationship:

class Post

public function categories(){
        return $this->belongsToMany('App\Category', 'post_category');
    }

and

class Category

public function posts(){
        return $this->belongsToMany('App\Post', 'post_category');
    }

How can I order categories by the count of the posts belonging to them for the past 24 hours and show the count of the posts from the past 24 hours belonging to that category?

Emmanuel-Ab
  • 321
  • 2
  • 15
  • Does this answer your question? [Laravel OrderBy relationship count](https://stackoverflow.com/questions/24208502/laravel-orderby-relationship-count) There's two answers, one shows how to use `sortBy()`, which is inefficient, the other uses correct `orderBy()` You'll have to slightly modify yours to only include from a date range, but the same logic applies. – Tim Lewis Sep 02 '20 at 19:43
  • But how to get the count of post for the past 24 hours and sort by then, the `withCount`return the whole count, not from the past 24 hours – Emmanuel-Ab Sep 02 '20 at 20:39
  • I think you can pass logic to `withCount()` to only return a subset, like `withCount('something', function($query){ // logic to filter by date })` (or similar) – Tim Lewis Sep 02 '20 at 20:41
  • 1
    Hmm I will try the callback and see what gets return, thanks – Emmanuel-Ab Sep 02 '20 at 20:47

0 Answers0