Reputation: 4783
I am trying to filter out objects by date. I am getting them by:
$events = Event::orderBy('event_date')->with('organizers')->get();
Which works fine...but now I'd like to split events to passed and not passed, so I tried with:
$result1 = $events->where('event_date', '<', Carbon::now());
But it returns empty collection. If I add get()
, it gives me an error. Strangely enough, if I do it like:
$result1 = $events->where('is_featured', 1);
This works, and returns only featured elements. What am I doing wrong?
Upvotes: 0
Views: 44
Reputation: 2362
As you state in your question, $events is a Collection, not a query. The where() method on the Collection works a little differently.
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. Something like this (just an example, the logic may need to be tweaked):
$filteredEvents = $events->filter(function ($item) use ($date) {
return (data_get($item, 'event_date') > $date) && (data_get($item, 'event_date') < $date->endOfDay());
});
Upvotes: 1