Figured it out
->whereRaw('(category IN (1,2,3) OR category IS NULL)')
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm at a loss here.
I have different statuses on a post: published, draft, etc. My query should only select published posts; on my development server it's working correctly, yet on my production server it's showing posts with a status of draft and I can't figure out why.
$posts = Post::latest('published_at')
->whereHas('user', function ($query) {
$query->where('status', 'active');
})
->when(auth()->check(), function ($query) {
$query->whereIn('category', defaultCategories());
$query->orWhere(function ($query) {
$query->whereNull('category');
});
})
->when(auth()->guest(), function ($query) {
$query->whereIn('category', defaultCategories());
})
->where('status', 'published')
->with('user.profile', 'pinned', 'comments', 'likes', 'tags')
->paginate(18);
I see where the problem is: it's the orWhere() constraint. Once I remove that everything works as expected. However, this then creates a problem as I need to select records `where categories = 1,2,3 or where categories = null and where status = 'published'
Tried $query->whereRaw('category IN (1,2,3) or category = NULL'); with the same, incorrect results.
Also tried: $query->whereRaw("(category IN (1,2,3) or category = NULL) and status = 'encoding'"); but it's been a while since I've written SQL queries so I'm a little rusty.
Figured it out
->whereRaw('(category IN (1,2,3) OR category IS NULL)')
Please or to participate in this conversation.