boisterouslobster
boisterouslobster

Reputation: 1293

Laravel compare timestamps in where statement

I have a block of code in which I am passing a Carbon date that looks like this:

2017-08-18 22:53:50.031922

And want to compare it to created_at time stamps of some records. However, it seems that the records are not being filtered out; is the comparison in the where statement valid?

$test = Auth::user()->tests()->with([
    'participants.testRecords' => function ($query) use ($latestCapture) {
        $query->select('id', 'score', 'test_id', 'participant_id', 'capture_timestamp', 'score', 'created_at');
        $query->where('test_records.created_at', '>', $latestCapture);
}])->findOrFail($id)->toArray();

Upvotes: 0

Views: 3547

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

If $latestCapture is instancej Carbon, you should rather use here:

$latestCapture->toDateTimeString()

to make sure you pass valid date string.

There is also one more thing - you should make sure created_at is filled in PHP and not in MySQL (this is default in Laravel) - if it's not you can expect time shifts when you have different time zones in PHP and MySQL

Upvotes: 2

Related Questions