skip to Main Content

I’m trying to get all posts that has at least 2 comments in the last 48 hours. I’m using the following code:

    $posts= Post::has( 'comments', '>', 1 )->whereHas( 'comments', function( $comments ) {
        return $comments->where( 'created_at', '>', Carbon::now()->subDays(2) );
    })->get()->toArray();
  1. has at least 2 comments is working fine.
  2. in the last 48 hours isn’t working.

4

Answers


  1. I think the problem is that you are using has() with whereHas() instead of doing that you should only use the whereHas() instead.

    $posts = Post::whereHas('comments', function($query) {
        $query->where('created_at' ,'>', Carbon::now()->subDays(2))
    }, '>', 1)->get();
    

    Querying Relationship Existence

    Login or Signup to reply.
  2. Your query is 'created_at', '>', Carbon::now()->subDays(2)

    It means created_at has been more than 48 hours from today

    But it should be less then 48 hours from today

    So, try this 'created_at', '<', Carbon::now()->subDays(2)

    Login or Signup to reply.
  3. maybe this will help

    $posts= Post::where( 'comments', '>', 1 )
                ->where( 'comments', function( $comments ) {
                    return $comments->where( 'created_at', '>', Carbon::now()->subDays(2) );
                })
                ->get()->toArray();
    
    Login or Signup to reply.
  4. <?php
    
    namespace AppHttpControllers;
    
    use IlluminateHttpRequest;
    use AppPost;
    use AppComment;
    
    class DemoController extends Controller
    {
        public function index()
        {
            $posts = Post::whereHas('comments', function($q) {
                $q->where('created_at', '>=', date('Y-m-d H:i:s', strtotime('-48 hours')));
            })->withCount('comments')->having('comments_count', '>=', 2)->get();
    
            return view('demo', compact('posts'));
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search