Laravel Collection – Condition in belongsToMany relationship with whereHas equivalent

  collections, laravel, php

I’ve 3 tables:

Users:

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

Conversations:

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

And User_Conversation:

Schema::create('conversation_user', function (Blueprint $table) {
    $table->unsignedInteger('conversation_id');
    $table->unsignedInteger('user_id');
    $table->dateTime('read_at')->nullable();
});

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);
        })->first();
    }
}

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