Reputation: 43
is it possible to use variables in a with()
?
for example:
groep::find(1)->with(['belongsToManyAgent'])
belongsToManyAgent
looks like:
public function belongsToManyAgent($ignoreVariables=true, $columns=['*'], $showBoth=false, $showRemoved=false) {
return $this->belongsToMany(
'App\Models\Agent', // doel model
'agent_groep', // pivot tabel
'groep_id', // local key
'agent_id' // foreign key
)
->when(!filter_var($ignoreVariables, FILTER_VALIDATE_BOOLEAN), function($query) use ($showRemoved) {
$query->select($columns)
->when(!filter_var($showBoth, FILTER_VALIDATE_BOOLEAN), function($query) use ($showRemoved) {
$query->where('verwijderd',$showRemoved);
})
->when(filter_var($showBoth, FILTER_VALIDATE_BOOLEAN), function($query) use ($showRemoved) {
$query->when(!filter_var($showRemoved, FILTER_VALIDATE_BOOLEAN), function($query){
$query->where('verwijderd','0');
});
});
});
}
can I access the variables in the function via with()
so that I can put $showRemoved
on true for example?
Upvotes: 0
Views: 843
Reputation: 7561
There are some options to further narrow down a relationship you have, like so:
$users = User::with(['posts' => function ($query) {
$query->where('title', 'like', '%code%');
}])->get();
See https://laravel.com/docs/9.x/eloquent-relationships#constraining-eager-loads . I don't think it is possible to actually pass an array of variables to your relation function since it is called internally without parameters.
Also you probably want to simplify that function name to just public function agents(...)
.
Upvotes: 1