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

Bervetuna's avatar

Order of where conditions in (eloquent) query

I made some sort of logbook for my organization. The admin creates Tags and gives authority to the users to create and read logbook messages with those specific tags. So far so good.

There is also a button 'show new messages since my last login'. Works fine, but there is a bug. When a user presses that button, he does get a list of logbook messages that were created since he last logged in, but the messages are not restricted to the ones he is authorized to read. He also sees messages with other tags than the once assigned to his account.

This is my (simplified, since there are some other filter possibilities) query:

$logitemsq = Logmelding::when($this->lastlogin, function($query){
            $query->where('created_at','>=',$this->lastlogin->created_at)
            ->where('datum','<=',Carbon::now()->format('Y-m-d'))
            ->orWhereHas('reacties', function($q){
                $q->where('created_at','>=',$this->lastlogin->created_at)
                ->where('datum','<=',Carbon::now()->format('Y-m-d'))
                ;
            })
            ;
        }) 
->where(function ($query) use ($tagsvanuser, $gebruikersvanuser, $afdelingenvanuser){

             $query->whereHas('tags', function($q) use ($tagsvanuser){
                $q->whereIn('tag_id',$tagsvanuser);
            })
            ->where(function($q) use ($gebruikersvanuser, $afdelingenvanuser){
                $q->doesntHave('gebruikers')
                ->orWhereHas('gebruikers', function($q) use ($gebruikersvanuser, $afdelingenvanuser){
                    $q->whereIn('gebruiker_id',$gebruikersvanuser)
                    ->orWhereHas('afdelingen', function($q) use ($afdelingenvanuser){
                        $q->whereIn('afdeling_id',$afdelingenvanuser);
                    })
                    ;
                })
                
                ;
            })
            ->orWhere('user_id',Auth::user()->id)
            ->orWhereHas('getagdecollegas', function ($q) {
                $q->where('user_id', Auth::user()->id);
            })
            ;
        })

When I change the order of the 2 elements in my query, the bug is gone. I don't understand why that is...

0 likes
2 replies
Sinnbeck's avatar

It seems that the problem is because you need to add proper scopes when using OR in queries

Its a bit hard to ready the query due to laracasts formatting. But it seems that your ->orWhereHas() at the start isnt in a proper scope. You do use scope later in the query though?

This is a scope

            ->where(function($q) use ($gebruikersvanuser, $afdelingenvanuser){
Bervetuna's avatar

@Sinnbeck Thanks!

Would that also explain why changing the order of the 2 parts of the query resolves the problem?

Please or to participate in this conversation.