Laravel select records older than 5 minutes?

前端 未结 3 422
遥遥无期
遥遥无期 2021-02-05 21:58

I have Laravel app where i check user loggedin regularly with a heartbeat for every 3 seconds (demo purpose, actually 5 minutes). For each beat I check if user\'s last activity

3条回答
  •  渐次进展
    2021-02-05 22:41

    The accepted answer is correct, but you could make it even cleaner by using a query scope on the User model (assuming that you have a User model)...

    $result = User::currentUser()->activityOlderThan(self::HEARTBEAT_INTERVAL)->get();
    

    Your User model would then have these functions:

    public function scopeCurrentUser($query)
    {
        return $query->where('id_user', '=', Session::get('id_user'));
    }
    

    And

    public function scopeActivityOlderThan($query, $interval)
    {
        return $query->where('last_activity', '>=', Carbon::now()->subMinutes($interval)->toDateTimeString());
    }
    

    Now your code is clean and easy to read :-)

提交回复
热议问题