Search code examples
phplaraveleloquentcollectionsintersection

Get intersecting rows between two Laravel collections


I have an accessor function for my User model which returns all the conversations of which a User is a participant.

    public function getConversationsAttribute()
    {
        $results = DB::select('SELECT * FROM conversation_user WHERE user_id = ?', [$this->id]);

        $conversations = array();

        foreach($results as $result){
            $conversation = Conversation::find($result->conversation_id);
            array_push($conversations, $conversation);
        }

        return $conversations;
    }

Now suppose I have two users $userA and $userB, how can I return the conversations of which both users are participants?

i.e., the common results between $userA->conversations and $userB->conversations

I imagine a UNION operator for duplicates is what is required.

What is the:

  1. MySQL solution
  2. Eloquent solution

Solution

  • Using intersect method of Laravel Collection, you can write

    collect($userA->conversations)->intersect($userB->conversations);