Laravel query for a range of time

10,957

You can make use of the same query as above to find the table rows between two times.

$query->whereTime('timestamp', '>=', \Carbon\Carbon::parse('06:00'))
     ->whereTime('timestamp', '<=', \Carbon\Carbon::parse('06:30'))

Dont concatenate date string like this,

$request->get('time').':00')  

This is not quite appropriate, and you might fail with this approach.

Share:
10,957
Cowgirl
Author by

Cowgirl

Updated on August 28, 2022

Comments

  • Cowgirl
    Cowgirl over 1 year

    I am looking for a way to make a query which compares time, morning - 6 to 9, day - 9 to 12 , evening 12 - 5

    Right now, I am using an select option in html

    <select name="time" id="time">
              <option disabled value="">Choose A Time</option>
              <option value="06:00 - 09:00">Morning - 06:00 - 09:00 </option>
              <option value="10:00 - 13:00">Day - 10:00 - 13:00 </option>
              <option value="14:00 - 18:00">Evening - 14:00 - 18:00</option>
            </select>
    

    And I am trying to query it like this, datetime I get it from the database and it's like 2017-12-13 06:15:00

        $query->whereTime('datetime', '>=', $request->get('time').':00')                    
        });
    

    I have no idea how I can compare a range of time, like compare 06:00-09:00 with 06:15

  • Cowgirl
    Cowgirl over 6 years
    Okay, but I have like 06:00-09:00 how can I use carbon parse on this, one for 06:00 and one for 09:00
  • Riccardo
    Riccardo over 6 years
    $morning_time_array = explode('-','06:00-09:00'); $morning_time_array[0] will be '06:00' also you should use whereBetween like: ->whereBetween('time', ['06:00', '09:00'])->get();