Search code examples
phplaravellumen

Laravel Nested Eager Loading how to use eloquent where condition from inside with nested


I'm looking for a way to use where condition in my laravel eloquent relationship with eager loading.

Here's my code

  $data = Model::with(['stage_chatbot'=> function($stage_chatbot){
     $stage_chatbot->select('id', 'customer_id','stage','created_at');
     $stage_chatbot->orderBy('id', 'asc');
  }])->whereIn('hot_leads_id', $getMaxHl)->orderBy('updated_at', 'desc');

  $data->where('stage_chatbot.stage', 'like', 'sampleValue')->get();
  return $data;

Thanks!


Solution

  • You can use whereHas() eloquent method like this.

    $data = Model::with(['stage_chatbot'=> function($stage_chatbot){
        $stage_chatbot->select('id', 'customer_id','stage','created_at');
        $stage_chatbot->orderBy('id', 'asc');
    }])->whereIn('hot_leads_id', $getMaxHl)->orderBy('updated_at', 'desc');
    
    $data->whereHas('stage_chatbot', function ($stage_chatbot) {
       $stage_chatbot->where('stage', 'like', 'sampleValue')
    })->get();
    return $data;