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

petritr's avatar
Level 15

condition inside query builder

I need to have an condition inside an relation query builder

 $jobs = Job::where('disabled_job', '=', '0')->with(['positions' => function ($queryPositions) {
       if(  $queryPositions->where('option', '=', '10')) ) {
            //Here i need again all $jobs 
       }

I need to write an condition then retrieve all jobs where option is equal to 10, not one entry.

At the moment it will return only one entry

0 likes
3 replies
bobbybouwmann's avatar

The query below should give you all the jobs that have disabled_job set to 0 and also where the options column of positions is set to 10

 $jobs = Job::where('disabled_job', '=', '0')->whereHas(['positions' => function ($query) {
    return $query->where('option', '=', '10');
});
1 like
petritr's avatar
Level 15

@bobbybouwmann thanks, how can i use this with 2 relations:

Job::where('disabled_hub', '=', '0')->with(['positions' => function ($queryPositions) {
            $queryPositions->where('queryPositions', '=', '10') );
        }, 'locations' => function ($queryLocations) {

How can i use that inside locations i need to have an condition like where inside region is equal to US Return all locations

bobbybouwmann's avatar

I don't really undestand your question, but you can do this

Job::where('disabled_hub', '=', '0')->with([
    'positions' => function ($queryPositions) {
        $queryPositions->where('queryPositions', '=', '10') );
    }, 
    'locations' => function ($queryLocations) {
        queryLocations->where(''region', 'US');
    }
])->get();

Or in your case a whereHas makes more sense

Job::where('disabled_hub', '=', '0')->with(['positions' => function ($queryPositions) {
    $queryPositions->where('queryPositions', '=', '10') );
}])->whereHas('locations', function ($queryLocations) {
    queryLocations->where(''region', 'US');
})->get();

Please or to participate in this conversation.