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

vincent15000's avatar

Query with where() and orWhere() ... "and where" ?

Hello,

I want that the three conditions are evaluated together.

            ->when($this->filtre_statut_mev != 0, function ($query) {
                $query->where('mevs.statut', $this->filtre_statut_mev);
            })
            ->when($this->filtre_statut_vente != '', function ($query) {
                $query->where('ventes.statut', $this->filtre_statut_vente);
            })
            ->when($this->recherche != '', function ($query) {
                $query->where('velos.marque', 'like', '%'.$this->recherche.'%')
                    ->orWhere('velos.modele', 'like', '%'.$this->recherche.'%')
                    ->orWhere('velos.annee', 'like', '%'.$this->recherche.'%')
                    ->orWhere('clients.nom', 'like', '%'.$this->recherche.'%')
                    ->orWhere('clients.prenom', 'like', '%'.$this->recherche.'%');
            })

The first two ones are well evaluated when $this->recherche is empty. But as soon as it is not empty, the first two conditions aren't evaluated, until it becomes empty again.

Why ? I have tested without the four ->orWhere() lines and all is ok. But I have to evaluate this for lines too with ->orWhere().

How is it possible to do that ?

Thanks for your answer ;).

Vincent

0 likes
2 replies
MichalOravec's avatar
Level 75

When you use orWhere you need to use logical grouping

Docs: https://laravel.com/docs/8.x/queries#logical-grouping

So that part has to be like

->when($this->recherche != '', function ($query) {
    return $query->where(function ($query) {
        $query->where('velos.marque', 'like', '%'.$this->recherche.'%')
            ->orWhere('velos.modele', 'like', '%'.$this->recherche.'%')
            ->orWhere('velos.annee', 'like', '%'.$this->recherche.'%')
            ->orWhere('clients.nom', 'like', '%'.$this->recherche.'%')
            ->orWhere('clients.prenom', 'like', '%'.$this->recherche.'%');
    });
})
1 like

Please or to participate in this conversation.