Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eloquent fetch records within recent 3 hours

I need to fetch all the records which is inserted between past 3 hours to current(now). I am using laravel framework(eloquent orm).

I tried this found here

$lb = \DB::table('myTable')->whereRaw('created_at = DATE_ADD(NOW(), INTERVAL -3 HOUR');

But it return NULL. Is there any way I can do using eloquent but not Raw Query?

Any Help would be appreciated.

like image 787
VijayRana Avatar asked Jul 27 '16 07:07

VijayRana


3 Answers

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();
like image 58
Hossin Asaadi Avatar answered Nov 12 '22 21:11

Hossin Asaadi


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

like image 23
Chris Avatar answered Nov 12 '22 22:11

Chris


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.

like image 9
Alok Patel Avatar answered Nov 12 '22 21:11

Alok Patel