Laravel Collection – Condition in belongsToMany relationship with whereHas equivalent

  collections, laravel, php

I’ve 3 tables:


Schema::create('users', function (Blueprint $table) {
    $table->string('name', 50)->nullable();


Schema::create('conversations', function (Blueprint $table) {
    $table->string('token', 50)->nullable();

And User_Conversation:

Schema::create('conversation_user', function (Blueprint $table) {

One conversation can have 2 users.

I have this class for Users:

class User extends Model {
    public function conversations(){
        return $this->belongsToMany(Conversation::class, 'conversation_user', 'user_id', 'conversation_id');

    public function getConversationWith($user_id){
        return $this->conversations()->whereHas('users', function ($q) use ($user_id) {
            $q->where('ml_users.user_id', $user_id);

My problem: I need to change the getConversationWith() method to:

public function getConversationWith($user_id){
    return $this->conversations->where('users.user_id', $user_id)->first();
    // Or this
    return $this->conversations->whereIn('users.user_id', [$this->id, $user_id])->first();

To get conversations with given user_id.

Is there a way to do this with collections ?

Thank in advance

Source: Laravel

Leave a Reply