eloquent fetch records within recent 3 hours

Laravel comes with Carbon, a nice library to handle dates, which can be used in combination with Eqlouent.

Example:

\DB::table('myTable')
    ->where('created_at', '>', 
        Carbon::now()->subHours(3)->toDateTimeString()
    );

More Information

For more fun date methods, check out these docs on Carbon http://carbon.nesbot.com/docs/#api-addsub


We can use PHP DateTime. Like this,

$date = new \DateTime();
$date->modify('-3 hours');
$formatted_date = $date->format('Y-m-d H:i:s');
$lb = \DB::table('myTable')->where('created_at', '>',$formatted_date);

In above code what we're doing is creating date string with PHP and using that in query.


add this scope to your model:

public function scopeRecent($query)
{
    return $query-> whereDate('created_at ' , '=',Carbon::today())
        ->whereTime('created_at' , '>',Carbon::now()->subHours(3));

}

then use the scope in controller :

    $posts= Post::recent()->pluck("id")->toArray();