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

MarlonV's avatar

Attach with pivot

I have an array with data (events) and a table event_user table Now I want that if the events are sold out, they will be put on a waiting list. The idea was to add queue pivot, and flag it whit a boolean when the available tickets are sold out. Therefore i have to make a calculation event->total_ticket - the subscribers. Got that part covered.

But honestly I have no idea where/how to start with adding stuff to a collection. Anyone have any suggestions or ideas?

    public function store()
    {
        $data = $this->validatedData();

		if( $eventcount < 0 ){
        $events = collect($data['events'])->mapWithKeys(function ($event, $key) use ($data) {
           return [$event => [
              'queue' => true,
           ]];
        })->toArray();
		}
else{
        auth()->user()->events()->attach($events);
		}
        return redirect()->route('volunteer.activities.index')->with('success', 'yeej.');
    }
    }

0 likes
3 replies
axeloz's avatar

Sorry but I don't really see the issue here. First you need to count the subscribers of an event:

$attendees = Attendee::where('event_id', ...)->where('status', 'confirmed')->count();

Then you check the max attendee value

if ($attendees >= $max_attendees) {
// then add to queue
}
else {
// subscribe to event
}
MarlonV's avatar

lets say event id 1 has 5 tickets left and id 2 has 0 tickets left. They are in the same collection. how do i flag id 2?

Or maybe is my approach wrong, and is it easyer to put it in a seperate table

jdc1898's avatar

If your events model has the number of tickets available, you can use the belongsToMany(‘event_users’) relationship. You can use Event/Listeners to check for ticket availability by comparing the count of records in event_users to the number of tickets for the event. I would consider adding a method to your events table to get the available number of tickets. ->getTicketAvailability

Please or to participate in this conversation.