vungo's avatar
Level 1

Eloquent ORM Eager Loading dynamic ?

Hello, i have 1 function reuse in model, but for many reason, this need with diffenrent. How i can control this ? In below, you can see i use 4 with, but i not need 4 with in all case, some with1, with2 or only with1. If pass with by params to function, it make function complex, not clearly. if clone to many function, it not a good solution.

return $this->with('with1')->with('with2')->with('with3')->with('with4')->where(...)->where(...)->get();

0 likes
3 replies
Snapey's avatar

you can remove the with conditions to scopes and then use those scopes to build more complex queries

vungo's avatar
Level 1

@Snapey hello, thanks for answer. You can explain detail it ? i also separate scope relation, but must to pass something to params to if else in function to call scope relation.

aleahy's avatar

Why not use a single with and list the relationships in an array?

return $this->with(['with1', 'with2', 'with3', 'with4'])
   ->where(...)
   ->where(...)
   ->get();

Then you can pass them in as an array as a parameter:

public function getStuff(array $includedRelationships) {
   return $this->with($includedRelationships)
      ->where(...)
      ->where(...)
      ->get();
}

...

$stuff = $this->getStuff(['with1', 'with2']);

Please or to participate in this conversation.