jackhammer013 jackhammer013 - 7 months ago 31
SQL Question

Get data from the last 8 hours in a datetime column Eloquent

I have a query using Laravel's Eloquent and I need a

where
clause that will get the data from the last 8 hours since the current timestamp. I can easily do that in a raw query like:

SELECT * FROM task_tracker.tasks WHERE created_at > DATE_ADD(NOW(), INTERVAL -8 HOUR);


But how do I do that in an eloquent format? The
tasks.created_at
is a Datetime Format. I have this currently:

$tasks = Task::join('users', 'tasks.added_by', '=', 'users.id')
->join('users AS x', 'x.id', '=', 'tasks.assigned_to')
->select([
'tasks.id',
'tasks.task_description',
'tasks.start_timestamp',
'tasks.end_timestamp',
'tasks.status',
'users.name',
'x.name AS assign',
'tasks.created_at'
// ])->where('tasks.created_at', '>', 'DATE_ADD(NOW(), INTERVAL -8 HOUR)');
])->where(DB::raw('tasks.created_at', '=', 'DATE_ADD(NOW(), INTERVAL -8 HOUR)' ));

dd($tasks);


I tried using
DB::raw
and a plain encloure in a single quote (the commented line) but does not work and doesn't get any data. I am using MySQL.

Answer

DB::raw has one parameter so try whereRaw like this:

->whereRaw('tasks.created_at = DATE_ADD(NOW(), INTERVAL -8 HOUR)