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

ajck's avatar
Level 1

How to join two Collections? (L5.4)

Hi, I'm building an appointments booking system, got a users table and an appointments table. Users can either be the appointment initiator (the one who creates the appointment) or the appointment recipient (the one who receives the appointment request).

I need to display a list of all appointments for a user, where they are either the initiator or the recipient, so I need to join the two separate collections I get, so I can pass that single list to the blade template to display. Using a standard one to many relationship, I have:

    // Get all of the user's appointments where they are an initiator: (one to many)
    public function appts_initiator()
        {
        return $this->hasMany('App\Appointment', 'initiator_id');
        }

    // Get all of the user's appointments where they are a recipient: (one to many)
    public function appts_recipient()
        {
        return $this->hasMany('App\Appointment', 'recipient_id');
        }

and controller code:

    public function listappointments()
        {
        // Get appt list for this user (initiator or recipient) from DB:
        $apptsinit = User::find(Auth::user()->id)->appts_initiator();
        $apptsrecpt =  User::find(Auth::user()->id)->appts_recipient();

        // NEED TO SOMEHOW JOIN/APPEND $apptsinit AND $apptsrecpt HERE TO FORM ONE COLLECTION:
        $all_appts_with_user    = ??? // Effectively $apptsinit + $apptsrecpt

        // Return view with appts (listed in blade template):
        return view('listappts', array('page' => 'listappts', $all_appts_with_user));
        }

How do I join the collections please, or is there a different way of achieving this?

Thanks. Alex

0 likes
5 replies
topvillas's avatar

Yeah, that's exactly what it should do. You can't have to keys that are the same in a dictionary.

ajck's avatar
Level 1

OK, fair enough, but how do I do what I originally stated - append a list of results (users) to another list of results, both of which are the same type, and even if there are duplicates in the results? Thanks

arukomp's avatar

How about this?

        $apptsinit = User::find(Auth::user()->id)->appts_initiator;
        $apptsrecpt =  User::find(Auth::user()->id)->appts_recipient;

        $all_appts_with_user = $apptsinit->splice(
            $apptsinit->count(),
            null,
            $apptsrecpt
        );

        return view('listappts', array('page' => 'listappts', $all_appts_with_user));

Please or to participate in this conversation.