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

imJohnBon's avatar

Is it possible to group where clauses in Eloquent?

I know I had seen that it was doable when using the DB facade, but I haven't found anything in the docs regarding it using the fluid Eloquent syntax.

0 likes
10 replies
usman's avatar
usman
Best Answer
Level 27

Yes, it is possible for example you can do something like:

User::where('username','john doe')
    ->where(function($query)
    {
        $query->where('age','>',30)
        ->orWhere('email','=','johndoe@xyz.com');
    })
    ->toSql();

The above statements will generate the following SQL:

select * from `users` where `username` = ? and (`age` > ? or `email` = ?)
20 likes
zizi_ove's avatar

It worked for me by this code:

public static function seachFiles($q, $categoryId)
{

    return static::where('category_id', '=' ,$categoryId)
                    ->where(function ($query) use ($q) {
                        $query->where('file_name', 'LIKE', "%$q%")
                                ->orWhere('file_code', 'LIKE', "%$q%")
                                ->orWhere('description', 'LIKE', "%$q%");
                    })
                    ->get();
}

hope this helps.

Please or to participate in this conversation.