Ron Brouwers Ron Brouwers - 4 months ago 57
PHP Question

Laravel search between dates no results when dates are the same (get results from today)

I have an

appointments table
in which I store the appointment start date and time in a
datetime
field. I have a bunch of methods which I use to get appointments that start on a specific date or between two given dates. For example:

Calendar Class:

public function today()
{
$start = Carbon::now()->hour('00')->minute('00')->second('00');
$end = Carbon::now()->hour('23')->minute('59')->second('00');

return Appointment::getAppointments($this->start, $this->end);
}

// public function tomorrow();
// public function thisMonth();


Appointment Model:

public static function getAppointments($start, $end)
{
return static::whereBetween('date', array(
$start->format('Y-m-d H:i'),
$end->format('Y-m-d H:i')
))->get();
}


As you can see I need to set the hour, minutes and seconds, because otherwise it will not return any results, if the start and end date are the same. Is it possible to simply do the following and still get the results from that date?

public function today()
{
$start = Carbon::now();
$end = Carbon::now();

return Appointment::getAppointments($this->start, $this->end);
}

public static function getAppointments($start, $end)
{
return static::whereBetween('date', array(
$start->format('Y-m-d'),
$end->format('Y-m-d')
))->get();
}

Answer

Try the following code

return static::whereBetween(Db:raw('DATE(date)'), array(
    $start->format('Y-m-d'),
    $end->format('Y-m-d')
))->get();

This will cast the DATETIME field to DATE