Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pllaguno's avatar

query where cluase is pulled from a relation

I have a user table, a credits table and a region table.

each credit is defined to a region by region_id in credits table, a User can have more than 1 region assigned to it.

What i am trying to achieve is to get all credits that are assigned to a user, so i have to cycle somehow through all of the user;s regions to include them in the query,

$pagination = $query->where(function($que){ 
            auth()->user()->regions()->each(function($item,$key){
                $que->orWhere('region_id',$item);
            });

        })->where('status_comercial',1)->with('Estado')->with('municipio')->with('gerente')->with('ejecutivo')->with('coordinador')->with('otro')->paginate($perPage);

i get undfined variable $que.. am i missing something or over complicating myself?

0 likes
2 replies
MichalOravec's avatar

Get all region ids

$regionIds = auth()->user()->regions()-pluck('id');

and then just user whereIn in your query

->whereIn('region_id', $regionIds)
squiaios's avatar

Previous answer is the way to do, but to answer your question, it's because the closure does not inherit the $que variable

    auth()->user()->regions()->each(function($item,$key) use ($que) {
        $que->orWhere('region_id',$item);
    });

Please or to participate in this conversation.