How to group a SQL statement in brackets/parenthesis

Laravel: How to group a SQL statement in brackets/parenthesis

It is very easy to chain where() methods together in Laravel like this:

  1. $posts = Posts::where("category",1)->where("published",true)->where("active",1)->get()

But this will create a long list of AND WHERE statements (You can also use orWhere for OR WHERE).

But what if you need to group your where statements in brackets (parenthesis)?

If you want something like this (with one part of the WHERE grouped by brackets (parenthesis):

    SELECT *
    FROM `orders`
        category = 1

        AND (
            featured = 1
            discounted IS NOT NULL

Then you will have to do something called parameter grouping.

Wrap those grouped parts of the where statement in something like this:

  1.     ...
  2.    ->where(function ($query) {
  3.             // put your grouped ->where() method calls here
  4.     }) ...

Real world example:

  1. DB::table('users')
  2.             ->where('name', '=', 'John')
  4.             ->where(function ($query) {
  5.             // Everything within this closure will be grouped together
  6.                 $query->where('votes', '>', 100)
  7.                       ->orWhere('title', '=', 'Admin');
  8.             })
  10.             ->get();

This would output:

select * from users where name = 'John' and (votes > 100 or title = 'Admin')

webdevetc profile pic

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This ( is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.


Comments and discussion about How to group a SQL statement in brackets/parenthesis

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to block access to certain referrers in Apache using .htaccess

How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to undelete a soft deleted Eloquent row?

How to hide directory listing in .htaccess?

How to check if two strings are anagrams in PHP?

How do Invokable Controllers work in Laravel?

How to replace whitespace with a single space

What is the null coalescing operator in PHP7?

How to get table column names from a database table in Eloquent?

What is the max size, by default, of GET variables?