How to write multiple AND queries inside OR query using closure

Sometimes it requires to setup eloquent builder to create queries which has multiple ands inside a or query.

For example, if we were to search "eloquent" in title field of posts tbl or in both foreign keys of community and topic tbl eloquent query might be following

Post::where('title','eloquent')->orWhere( function ($query) ) {
	$query->where('community_id', 5) // here, 5 is the id of 'eloquent' row eloquent in community table
	      ->where('topic_id', 4) // here, 4 is the id of 'eloquent' row eloquent in topics table
})->get()


Above, multiple ands are used inside orWhere closure to get the desired result.

Hence, this will produce following raw sql

select * from posts where title = 'eloquent' OR ( community_id = 5 AND topic_id = 4 )

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent