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

DanielRønfeldt's avatar

Eloquent equivalent of "andWhere", is there such a thing?

Okay, I've got a simple one for y'all Eloquent gurus :)

Say there are two columns, category, and tag, on which models retrieval from the DB can be performed. I know it's possible (and straightforward) to retrieve models that match either criterion, like, for instance, in my code below.

But how can one retrieve only the models that match BOTH criteria? Some equivalent of a query operator method like andWhere()?

Thanks in advance.

$articles = App\Article::with('user')
                                    ->where("category", "LIKE", "%$searchValueCat%")
                                    ->orWhere("tag", "LIKE", "%$searchValueTag%")
                                    ->orderBy( 'id', $order_by_dir )
                                    ->paginate($length);
0 likes
5 replies
Nakov's avatar

If you change this orWhere to where that's doing and where and not or.. if you use or I would suggest you group them like this:

$articles = App\Article::with('user')
	->where(function($query) use ($searchValueCat, $searchValueTag) {
        $query->where("category", "LIKE", "%$searchValueCat%")
            ->orWhere("tag", "LIKE", "%$searchValueTag%");
    })
    ->orderBy( 'id', $order_by_dir )
    ->paginate($length);
1 like
tykus's avatar

and is implied whenever you chain where Builder methods, you have an orWhere currently, change it to where

1 like
DanielRønfeldt's avatar

@nakov and @tykus thank you both for your help! I honestly had no idea that one could chain multiple where method calls.

@nakov I'm wondering what's the benefit of groupping the orWhere methods like you suggested? Thank you! :)

tykus's avatar

@DanielRønfeldt whenever you have an orWhere, you likely want a logical grouping:

where A and B or C
// is different from
where A and (B or C)
1 like

Please or to participate in this conversation.