Hkm Sadek
Hkm Sadek

Reputation: 3209

How to use conditions inside laravel eager loading

please see my message table schema

Schema::create('messages', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('conversation_id')->unsigned()->index();
        $table->foreign('conversation_id')->references('id')->on('conversations');
        $table->integer('last_sender')->unsigned();
        $table->foreign('last_sender')->references('id')->on('users');
        $table->string('msg');
        $table->integer('deleted')->unsigned();
        $table->integer('seen')->unsigned();
        $table->timestamps();
    });

And this is the current query I am using

Message::whereIn('conversation_id',$msgs)
         ->with(array('last_sender'=>function($query){
                $query->select('id','userName','profilePic', 'firstName','lastName');
          }))
         ->orderBy('conversation_id', 'desc') 
         ->groupBy('conversation_id')
        ->get();

As you can see I am Eager Loading last_sender. But I want to load it based on a condition. For example, If a user is logged in and his id is 10 and last_sender IS NOT=10 then I want to load because I only want to load if the currently logged in user's id is not present in the last_sender column.

Any help is highly appreciated. Thank you.

Upvotes: 1

Views: 2788

Answers (1)

dbr
dbr

Reputation: 1047

Message::with([
  'last_sender' => function($q) use ($userId = Auth::user()->id) {
    $q->where('id','!=',$userId)
  }
])->get();

to eager load the relation under condition.

Message::whereHas(
  'last_sender', function($q) use ($userId = Auth::user()->id) {
    $q->where('id','!=',$userId)
  }
)->get();

to load the model instance if it has relation with condition.

Hope this is what you asked for?

Upvotes: 2

Related Questions