I'm working on an event booking system. When the user searches for a date range, I use a function inside my Event model that checks if the event is available. My search function currently works as follows:
$events = Event::where('name', 'LIKE', '%' . $request->get('term') . '%')
->where('accepted',1)
->orWhere('description', 'LIKE', '%'.$request->get('term').'%')
->orWhere('city', 'LIKE', '%'.$request->get('term').'%')->paginate(15);
$availableEvents = new Collection();
if ($request->get('from') !== '' AND $request->get('to') !== '') {
foreach($events as $key => $event) {
if ($event->is_available($request->get('from'), $request->get('to'))) {
$availableEvents->add($event);
}
}
}
else {
$availableEvents = $events;
}
return view('frontend.events.results', ['events' => $availableEvents, 'request' => $request]);
I can't check availability inside the query builder so I have to loop through. I'm using a Illuminate\Database\Eloquent\Collection because I can't remove events from the paginated thing I get from the query builder.
Is there some way to convert the Eloquent Collection to a paginated collection?
Thanks in advance!
P.S. I'm passing $request to the view to use appends() so I can retain the query string parameters during pagination.
EDIT: The is_available function
public function is_available($from, $to) {
$from = Carbon::createFromFormat('d-m-Y', $from);
$to = Carbon::createFromFormat('d-m-Y', $to);
foreach($this->not_availables as $notAvailable) {
$notAvailableFrom = Carbon::createFromFormat('Y-m-d', $notAvailable->from);
$notAvailableTo = Carbon::createFromFormat('Y-m-d', $notAvailable->to);
if ($from->gte($notAvailableFrom) OR $to->lte($notAvailableTo)) {
return false;
}
}
return true;
}