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

dajoeberlei's avatar

Get Collection of Related Model from existing Collection of Base Model

Hi, i couldn't figure out how to name the Title precise :). I have following Issue. I want to find an elegant way to get the following Collection.

I have an Event model and one specific instance in $event. The Event Model has a hasMany Relationship to Bookings. So $event->bookings. The Booking has a belongsTo Relationship to a User. so $booking->user

So $event->bookings returns a collection of Bookings where there is obviously a "user_id" in each booking.

In the following situation i already got the $event->bookings and now i need a Collection of Users that are referred to in this already given "$event->bookings" collection. What is an elegant way to get those instead of

$users = collect();
foreach($event->bookings as $booking) {
	$users->push($booking->user);
}
return $users;

Is there a more elegant one-liner? Some thing like

$users = collect($event->bookings->each->user); // which is nonsense but you get the point what im looking for)

Edit: This is my very first post on laracast, i couldn't find what i needed here in the forums. Probably someone answered it already in other words but i couldnt find it sorry. Also i hope putting this in the "Laravel" Section was fair enough, since i don't want this to be solved through Eloquent, more through Collection methods or something like that.

0 likes
3 replies
kevinbui's avatar

What you did is totally fine:

$users = $event->load('bookings.user')
    ->bookings
    ->map->user;

In addition, A very popular approach is to create a many to many relationship between the Event and the User model, using Booking as a pivot.

class Event extends Model
{
    public function bookedUsers()
    {
        return $this->belongsToMany(User::class, 'bookings', 'event_id', 'user_id');
    }
}

// Then you can simply call
$event->bookedUsers;

Can a user make one OR numerous bookings for a single event? If the latter is true, there might be duplicated users from that relationship and you can do this:

$event->bookedUsers->unique();
1 like
Snapey's avatar
$event->load('bookings.user');

if you need to load all of them, it would be better to see if you can do this when you originally get the events, not trying to backfill them later

$events->each(function($event) {
	$event->load('bookings.user');
});

but this will cause as many calls to the bookings table as you have events (an n+1 issue)

1 like

Please or to participate in this conversation.