3 months ago

Append an attribute to collection without causing N+1 issue

Posted 3 months ago by thebigk

I'm trying to find out a way to append an attribute to the returned collection without causing N+1 issue.

I've to fetch a list of events and the collection should have an attribute attending (true/false) based upon whether I'm attending the event or not.

Here's what I have:

Event.php (Model)

class Event extends Model
    public function attendees()
        return $this->belongsToMany(User::class, 'event_attendees')->withTimeStamps();

    public function getAttendingAttribute()
        return $this->attendees()->where('user_id', '=', auth()->id());

The event_attendees has simple structure event_id | user_id and acts as the pivot table between the User and Event model.

Now, on the events index page, I need to show the user which events they are attending. My controller has the following

public function index()
    $events = Event::where('start_date', '>', now())->paginate(30);

    return $events; // Testing

Above code causes N+1 problem because of the Attending attribute. I'm not sure what changes can I make in order to keep my blade template simple -

    <div> Attending </div> 

I thank you for your time in advance.

Please sign in or create an account to participate in this conversation.