Kaizokupuffball
Kaizokupuffball

Reputation: 2843

Laravel eloquent where date is equal or greater than DateTime

I'm trying to fetch relational data from a model where the date column is higher or equal to the current time.

The date column is formated as this: Y-m-d H:i:s

What I'm trying to do is to grab all rows where the Y-m-d H:i:s is in the future.

Example: lets assume the date is 2017-06-01 and the time is 09:00:00 Then i would like got all rows where the date is in the future, and the time is in the future.

Currently my code looks like this, and it's almost working but it doesn't grab the rows where the date is the current day.

public function customerCardFollowups() {
    return $this -> hasMany('App\CustomerCardFollowup', 'user_id') -> whereDate('date', '>', Carbon::now('Europe/Stockholm')) -> orderBy('date', 'asc') -> take(20);
}

What am I doing wrong?

Upvotes: 47

Views: 164017

Answers (4)

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

Sounds like you need to use >=, for example:

->whereDate('date', '>=', Carbon::now('Europe/Stockholm'))

Upvotes: 63

Abdul Razak Zakieh
Abdul Razak Zakieh

Reputation: 774

Using whereDate will compare the date only and ignore the time. So your solution will give the records that are at least dating one day later and the records that are in the same day but with later hours will not be included.

If you use >= as suggested in other answers, you will get records starting from the current date and those ones who are even before the determined hour.

One solution for this is comparing using MySQL functions in whereRaw. In your code the condition for the date will be like this:

-> whereRaw("date > STR_TO_DATE(?, '%Y-%m-%d %H:%i:%s')" , Carbon::now('Europe/Stockholm')->format('Y-m-d H:i'));

In the code, I changed the format of Carbon date to match a specific format where you can use whatever format you want and put the same format in the STR_TO_DATE function.

Upvotes: 11

Amin Shojaei
Amin Shojaei

Reputation: 6588

For Laravel's TestCases:

$this->assertDatabaseHas('my_table', [
    'name' => $name,
    [ 'updated_at', '>=', $updatedAt ] // $updatedAt is a Carbon object
]);

Upvotes: 2

Bassil Qureshi
Bassil Qureshi

Reputation: 581

Here you can use this:

->where('date', '>=', date('Y-m-d'))

Upvotes: 47

Related Questions