Aditya Rahmatullah
Aditya Rahmatullah

Reputation: 23

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!

Upvotes: 2

Views: 297

Answers (3)

Jignesh Joisar
Jignesh Joisar

Reputation: 15115

try this one

using use keyword in laravel

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

for more information how to used use keyword in anonymous function see

Upvotes: 1

MD. Jubair Mizan
MD. Jubair Mizan

Reputation: 1560

Define a varibale on your Search Input field or value and pass this through use on your model query

Try this

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

Upvotes: 0

Raj
Raj

Reputation: 421

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;

Upvotes: 0

Related Questions