jackhammer013 jackhammer013 - 2 years ago 102
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

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
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')
'x.name AS assign',
// ])->where('tasks.created_at', '>', 'DATE_ADD(NOW(), INTERVAL -8 HOUR)');
])->where(DB::raw('tasks.created_at', '=', 'DATE_ADD(NOW(), INTERVAL -8 HOUR)' ));


I tried using
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 Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download