NicoHood
NicoHood

Reputation: 1093

Laravel eloquent compare datetime with query builder

I'd like to compare datetime values (with date AND time). First I tried this, but it does not work, as it only compares the date, not the time:

$events = $events->whereDate('end', '>=', $input['after']);

I thought that a simple where would help, but it does not:

$events = $events->where('end', '>=', $input['after']);

The reason for that is, that my input value is 2022-10-10T00:00:00 and the database read gives 2022-10-10 00:00:00 (the T in the middle was added in the input).

I'd like to stick to the isoformat (using the T), however inside the database that format gets casted to a value without T it seems. The reason for that might be the cast in the model: 'end' => 'datetime',

What would be the best way to solve this issue and compare datetime objects (and how)?

  1. Change the model cast
  2. Cast the input

Upvotes: 1

Views: 1372

Answers (1)

Xupitan
Xupitan

Reputation: 1681

What would be the best way to solve this issue and compare datetime objects

The best way is still to convert the input with the data type format of the date and time column

You can use : $dateConvert = date('Y-m-d H:i:s', strtotime($input['after']));

But I suggest you use carbon library :

$dateConvert = \Carbon\Carbon::parse($input['after'])->format('Y-m-d H:i:s');

And :

$events = $events->where('end', '>=', $dateConvert );

Upvotes: 2

Related Questions