Filtering eloquent Laravel collections using filtering method
$events=Event::all();
if (isset($scheduling) && $scheduling!=="All")
{
$events = $events->filter(function($event) use ($scheduling)
{
return $event->where('scheduling',$scheduling);
});
}
$events=$events->get();
can someone fix this code. the internal filter is not working. the results will be the same or without filters applied. I need to apply tray filters like this based on conditions
source to share
You don't need to use a condition in it, you can just return true
or false
from callback
depending on the selection condition.
Below code will only save those events
that pass the given test of truth:
$events=Event::all();
if (isset($scheduling) && $scheduling!=="All")
{
$events = $events->filter(function($event) use ($scheduling)
{
return $event->scheduling == $scheduling;
});
}
dd($events); //Collection
source to share
Another answer correctly explains why what you are doing doesn't work, but here's another option.
Instead of pulling everything out of the database and then applying filters to the collection, you can use a builder to let the database filter.
$query = Event::query();
if (isset($scheduling) && $scheduling !== "All") {
$query = $query->where('scheduling', '=', $scheduling);
}
// add more wheres as needed
$events = $query->get();
source to share