skip to Main Content

I have 2 separate columns for the date: the date itself in YYYY-mm-dd format, and a time column in time(7) datatype, for example 11:15:10.0000000

How can I check for rows that are in the future?

I can get the first part, for the day itself:

MyModel::where('date', '>=', Carbon::today())->get()

But when I try adding the time it doesn’t work:

MyModel::where('date', '>=', Carbon::today())->where('time', '>', Carbon::now()->format('H:i'))->get()

because they are separate and now even though the date is in the future, the time is separate so there may be a situation where the time doesn’t match. So I somehow need to have both the date and the time related to it in the future, not separately

2

Answers


  1. Try to combine both the columns in a single condition.

    $now = Carbon::now();
    
    MyModel::whereRaw("CONCAT(`date`, ' ', `time`) >= ?", [$now->toDateTimeString()])->get();
    

    For SQL Server try following

    MyModel::whereRaw("CONVERT(datetime, date + ' ' + CONVERT(varchar, time, 121)) >= ?", [$now->toDateTimeString()])->get();
    

    Query conversion may need to update, for more information try documentation

    Login or Signup to reply.
  2. Comparison via datatype is important here. So, you can use orWhere to combine 2 different conditions. For this, you will need to pass a callback to group conditions inside one for the AND in where conditions in raw format.

    <?php
    
    MyModel::where('date', '>', Carbon::today())
            ->orWhere(function($query){
                $query->where('date', '=', Carbon::today())
                      ->where('time', '>', Carbon::now()->format('H:i'));
            })->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search