Laravel selects records older than 5 minutes?

I have a Laravel application where I regularly check the loggedin user with a beating for every 3 seconds (demo target, actually 5 minutes). For each bit, I check to see if the last user activity with the current time is also 5 minutes. If so, log out.

Here is my code:

$result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->where('last_activity','>=',"now() - interval 5 minute")->get(); if(!empty($result)) return Redirect::to('/logout'); else return Response::json('still-alive'); 

My problem is that this does not work. If I changed the operand to <= , it will exit the system immediately before 5 minutes, if the operand is >= , even after 5 minutes it will not exit the system, can anyone explain why?

-Edit -

Thanks for all the answers, I solved my problems by changing the code:

 $result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->first(); if(!empty($result)) if(strtotime($result->last_activity) < strtotime("-5 minutes")) return Redirect::to('/logout'); else return Response::json('still-alive'); else return Response::json('no-record'); 
+6
source share
3 answers

Assuming your business logic is correct, try using PHP instead of the SQL string in the where clause:

 $date = new DateTime; $date->modify('-5 minutes'); $formatted_date = $date->format('Ymd H:i:s'); $result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->where('last_activity','>=',$formatted_date)->get(); 

In addition, it is recommended that you always output executed SQL queries to make sure that Laravel behaves as expected:

 $queries = DB::getQueryLog(); 
+24
source

The accepted answer is correct, but you can make it even cleaner by using the request area in the User model (assuming you have a user model) ...

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

The user model will have the following 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 :-)

+28
source

You can use whereRaw() :

 $result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->whereRaw('last_activity >= now() - interval 5 minute')->get(); 

or

 $result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->whereRaw('last_activity >= now() - interval ? minute', [5])->get(); 
+1
source

Source: https://habr.com/ru/post/956348/


All Articles