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

timgavin's avatar

Eloquent query showing wrong result

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);

Update

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.

0 likes
2 replies
timgavin's avatar
timgavin
OP
Best Answer
Level 11

Figured it out

->whereRaw('(category IN (1,2,3) OR category IS NULL)')
crnkovic's avatar

can you paste here the SQL query generated by the query builder?

maybe try this:

->when(auth()->check(), function ($q) {
    $q->where(function ($q) {
        $q->whereIn('category', defaultCategories())->orWhereNull('category');
    });
})

I believe the issue is due to logical grouping.

Edit: Reading your solve is making me sure it was a mistake due to logical groups.

Please or to participate in this conversation.