Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jcc5018's avatar

Where am I going wrong with this lazy load set up- finding upcoming events for a group

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.

0 likes
5 replies
bobbybouwmann's avatar

So first of all, you need to make sure that your relationship is set up correctly. If you use the current syntax I expect that your table is called event_group in the database. That is correct, right?

For querying the data. When using load it will add the data to the current model. You can't directly call take on it. Also, load works great if you have one relationship but in your case, you need to fetch the same relationship twice with different query conditions.

In that case, load makes it more complex. You can get around it by directly quering on the relationship. Try this:

$newEvents = $group->groupEvents()
	->where('start_date', '>', Carbon::now())
	->orderBy('start_date', 'asc')
	->take(5);

$oldEvents = $group->groupEvents()
	->where('start_date', '<=', Carbon::now())
	->orderBy('start_date', 'desc')
	->take(5);

Let me know if this makes sense to you ;)

jcc5018's avatar

I do have that in my DB. Now unfortunately after your fixes, I am getting the Trying to get property 'name' of non-object error on my view.

jcc5018's avatar

Ok So i changed things up a little as the provided code wasnt providing a result.

    {
        // $group->load('groupEvents');

        // $newEvents = $group->groupEvents->where('start_date', '>', Carbon::now())->sortBy('start_date', 'asc')->take(5);
        
        // $newEvents = $group->load(['groupEvents' => function ($query) {
        //     $query->where('start_date', '>', Carbon::now())->orderBy('start_date', 'asc');
        // }])->take(5);


$newEvents = $group->groupEvents
	->where('start_date', '>=', Carbon::now())
	->sortBy('start_date')
	->take(5);

$oldEvents = $group->groupEvents
	->where('start_date', '<', Carbon::now())
	->sortByDesc('start_date')
	->take(5);
 
        $slug = $group->slug;
        return view('frontend.groups.sections.events', compact('group', 'slug', 'newEvents','oldEvents'));
    }

I used sortby instead, and I do get my events displayed. But I should have 3 new events and 2 old events. but they are all showing in the past events section. So I feel like the carbon section still isnt working either.

bobbybouwmann's avatar
Level 88

Aah yes! Sorry I provided you with the wrong query.

To be clear here. When doing $group->load('groupEvents') it will load all group events on the group model. If you for example have 1000 events connected you will get all those models back.

You can't do this in one query as far as I know since you can't alias. What you can do is create a relationship with the correct query

public function groupEvents()
{
		return $this->belongsToMany(Event::class);
}

public function groupEventsFromThePast()
{
		return $this->belongsToMany(Event::class)
				->where('start_date', '<=', Carbon::now())
				->orderBy('start_date', 'desc');
}

public function groupEventsInTheFuture()
{
		return $this->belongsToMany(Event::class)
				->where('start_date', '>', Carbon::now())
				->orderBy('start_date', 'asc');
}

Now you can query it in once and add the numbers you want as well

$group->load([
		'groupEventsFromThePast' => function ($query) {
				$query->take(5);
		}),
		'groupEventsInTheFuture' => function ($query) {
				$query->take(5);
		}),
]);

@foreach ($group->groupEventsFromThePast as $event)
		{{ $event->name }}
@endforeach

This should put you in a better direction ;)

jcc5018's avatar

That worked after taking out the extra set of Parentheses you had in there.

That you for your help.

I guess the next question is, and one of the reasons I have a hard time with the docs. How do you know when a method eleoquent string is better off in the model vs the controller or any of the other possible places you can pull from.

I get hung up on this all the time as the docs never really seem to give all the details as to the best place to put something. Each different way would have a different method of referencing that method, and I tend to get confused and hung up on what goes where and why.

Please or to participate in this conversation.