7 months ago

Simple way of Deep whereHas

Posted 7 months ago by muzafferdede

I have a case where i need to query multiple level of whereHas method on the model, which i need to loop through an array to figure out the how deep it will go. As in the example:

public function apply(Request $request, $query, $value)
    return $query->whereHas('sales', function ($sale) use ($value) {
        $sale->whereHas('stores', function($store) use ($value) {

i would like to achieve this using a loop something like dynamic as:

$this->parents = ['sale','store'];

return $query->when($this->parents, function ($query, $parent) use ($value) {
    $query->whereHas($parent[0].'s', function ($parent1) use ($value) {
        $parent1->whereHas($parent[1].'s', function ($parent2) use ($value) {
            $parent2->where('id', $value);
}, function ($query) use ($value) {
    $query->where('id', $value);

any easy way to achieve this? Thank you

Please sign in or create an account to participate in this conversation.