Its been a bit since I worked on this project, so probably forgetting some basics again, but after looking at the docs I'm not getting what I need. I have a group/ event M:M relationship.
I'd like to display the top 5 events coming up in the future, as well as the last 5 past events. But I'm either getting every event in the DB or I get nothing. I'm not getting the specific events related to the group.
This is my controller setup. Only using new events as I expect the past events will simply switch the operator.
public function events(Group $group)
{
//TRIED THIS
// $group->load('groupEvents');
// $newEvents = $group->groupEvents->where('start_date', '>', Carbon::now())->sortBy('start_date', 'asc')->take(5);
//AND THIS
$newEvents = $group->load(['groupEvents' => function ($query) {
$query->where('start_date', '>', Carbon::now())->orderBy('start_date', 'asc');
}])->take(5);
$slug = $group->slug;
return view('frontend.groups.sections.events', compact('group', 'slug', 'newEvents'));
}
View:
<div class="row">
<div class="col-12">
<h3>Upcoming Events</h3>
@foreach($newEvents as $event)
<p>{{$event->name}}</p>
@endforeach
</div>
</div>
Group Model
public function groupEvents()
{
return $this->belongsToMany(Event::class);
}
If i add an ->get(); I get all events instead of only events for the group, and they also do no appear to be sorting by date. I actually do not have any start dates set in the DB except for the specific records for the group I'm currently testing on, so really nothing but 6 records should show up. Actually less, cause I made two events have dates in the past. So that part does not seem to be working either.
If I need to do a Group::with('groupEvents') first, do i then need to specify which group I need, even though the method should be loading that group function events(Group $group)
Sorry for the basic questions, I'm just getting frustrated when I think I'm copying the examples from docs and other sources, yet things don't work as I expect. Obviously I'm missing something.