1

Laravel support collection does not work with the date and time. how can I solve it?

$timings = collect([]);

for ($i = 1; $i < 24 ; $i++) {
    $timings->push([
        'start_time' => $i.':50:34'
    ]);
}

Above loop is for the generate 24 hours timings for the example.

When we make this then works fine but include unnecessary timings also.

$timings->where('start_time', '<=', '11:59:59')->where('start_time', '>=', '00:00:00');
$timings->where('start_time', '>=', '12:00:00')->where('start_time', '<=', '23:59:59');

Please help me with this.

1 Answers1

1

You seem to be using strings instead of date objects. strings are not suitable for the comparisons you are doing.

You can use Carbon to create nice date objects (Carbon is already included in laravel)

$timings = collect([]);

for ($i = 1; $i < 24 ; $i++) {
    $timings->push([
        'start_time' => Carbon::createFromTimeString($i.':50:34', 'Europe/London')
    ]);
}

As this answer states:

For Collections, the where() method does not accept an operator. It only does equality comparisons. The first parameter is the key, the second is the value, and the third is a boolean to flag a loose comparison (==) vs a strict comparison (===).

What you're looking for is the filter() method. You pass in a Closure that does your date comparison. If the Closure returns true, the item stays in the Collection. If it returns false, the item is removed from the Collection.

The filter in your case would look like this:

$timings = $timings->filter(function ($item) {
    return (data_get($item, 'start_time') <= Carbon::createFromTimeString('11:59:59', 'Europe/London')) 
        && (data_get($item, 'start_time') >= Carbon::createFromTimeString('00:00:00', 'Europe/London'));
});
Mike
  • 852
  • 9
  • 17