Laravel change date format in where clause to match Carbon::now()

Klav picture Klav · Dec 29, 2017 · Viewed 7.8k times · Source

I need to select entries based on dates happening in the future and the
entries contain the date format:

12/30/17

I'm trying to format the date and compare to Carbon::now() timestamp, with no luck.

$now = \Carbon\Carbon::now();

$bookings = DB::table('booking')
    ->select('booking.*')
    ->where('booking.uid', '=', Auth::id())
    ->where(DB::raw("(DATE_FORMAT(booking.date,'%Y-%m-%d 00:00:00'))"), ">=", $now)
    ->get();

Answer

aynber picture aynber · Dec 29, 2017

You'll need to use STR_TO_DATE to convert the string.

$bookings = DB::table('booking')
    ->select('booking.*')
    ->where('booking.uid', '=', Auth::id())
    ->where(DB::raw("(STR_TO_DATE(booking.date,'%m/%d/%y'))"), ">=", $now)
    ->get();

STR_TO_DATE will convert 12/30/17 to 2017-12-30