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

Wizix's avatar
Level 1

Help on a complex query

Hi guys,

I have two models, User and Event. An user can own events (he is the creator of the event) and he also can be a guest of many events. The first relation is a OneToMany and the other one is a ManyToMany (an event can have many guests and an user can be a guest of many events).

This is my User model :

class User extends Authenticatable
{
    /**
     * Get the events of the user.
     */
    public function owned_events()
    {
        return $this->hasMany('App\Event', 'owner_id');
    }

    /**
     * Get the events list.
     */
    public function events()
    {
        return $this->belongsToMany('App\Event')
                    ->using('App\Invitation')
                    ->withPivot('status')
                    ->withTimestamps();
    }
}

This is my Event model :

class Event extends Model
{
    /**
     * Get the owner of the event.
     */
    public function owner()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * Get the guests list.
     */
    public function guests()
    {
        return $this->belongsToMany('App\User')
                    ->using('App\Invitation')
                    ->withPivot('status')
                    ->withTimestamps();
    }
}

This is where I need a complex query. I need to retrive all events (owned and guest) of a user and order them by the date field, in a single collection, so I can do a loop on it on my blade view.

I know how to retrieve the owned events or where the user is the guest but not the two together...

I hope that someone can help me.. If you need more information, ask me!

Thanks!

0 likes
2 replies
IgorBabko's avatar
Level 36

Hello -

You could simply merge two collections like so:

$allEvents = $user->owned_events->merge($user->events);
m7vm7v's avatar

Both the events should be now a collections. So now you can simply combine them


$combined = $collection1->combine($collection2);

$combined->all();

Please or to participate in this conversation.