you can refactor this into a single query and then chain on different conditions if your inputs demand it.
Also look into the ->when query parameter
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a table categories with columns ('id' 'name', ......... 'parent_id', 'deleted_at', ...)
Now I want to get all records using withTrashed() but where 'id' != $exceptId' AND 'parent_id' != $exceptId'
Here is my function
public function getCategories($exceptId = null, $withTrashed = false) {
if ($exceptId && $withTrashed){
// This is not giving me desire results
$categories = $this::withTrashed()->where('id', '!=', $exceptId)->where('parent_id', '!=', $exceptId)->get();
dd($categories);
}elseif ($exceptId){
$categories = $this::where('id', '!=', $exceptId)->where('parent_id', '!=', $exceptId)->get();
}elseif ($withTrashed){
$categories = $this::withTrashed()->with([
'parent' => function ($query){
$query->withTrashed();
}
])->get();
}else {
$categories = $this::get();
}
return $categories;
}
Help me to solve this..
OK, the actual problem was with NULL and I modify @matt_panton 's solution a little bit and this worked for me
public function getCategories($exceptId = null, $withTrashed = false) {
$categories = $this->newQuery()
->when($withTrashed, function ($query){
$query->withTrashed();
})
->when($exceptId, function ($query) use ($exceptId){
$query->where('id', '!=', $exceptId)->where(function ($q) use ($exceptId){
$q->where('parent_id', '!=', $exceptId)->orWhere('parent_id', null);
});
})
->when(is_null($exceptId), function ($query){
$query->with([
'parent' => function ($parentQ) {
$parentQ->withTrashed();
}
]);
})
->get();
return $categories;
}
Please or to participate in this conversation.