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

Haseeb69's avatar

Nested wherehas closure function not working correctly

need help with this nested closure function as it is not working perfectly. This chunk of code is part of a bigger sql query , and problem lies in this part only any help will be appreciated

  $browse_verticals = $browse_verticals->distinct()->with("verticals")->with([
                    "document_types" => $closure = function ($query) use ($document_array, $key) {
                        $query->whereIn('document_type_id', $document_array);
                        if ($key != "") {
			//problem is here it is working  fine for above statement but not for this key .
                            $query->whereHas(
                                'titles',
                                function ($query) use ($key) {
                                    $query->orwhere("title", 'LIKE', '%' . $key . '%');
                                }
                            );
                        }
                    }
                ])->whereHas('document_types', $closure)->distinct();
0 likes
4 replies
Sinnbeck's avatar

@Haseeb69 so check the query with debug bar and show it along with what you want it to do

Please or to participate in this conversation.