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`
    WHERE
        category = 1

        AND (
            featured = 1
            OR
            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')
  3.  
  4.             ->where(function ($query) {
  5.             // Everything within this closure will be grouped together
  6.                 $query->where('votes', '>', 100)
  7.                       ->orWhere('title', '=', 'Admin');
  8.             })
  9.  
  10.             ->get();

This would output:

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

webdevetc profile pic
webdevetc

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



More...


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

What does 'final class' and 'final function' (final method) mean in PHP?

How to remove .php from the end of URLs with .htaccess

How do you access the php://input stream?

An overview of every main PHP array function

What does PEAR stand for?

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

How to redirect your website to a new domain/location in .htaccess

What are the predefined variables in PHP?

What are the SPL Iterators in PHP?

How to make Apache force download of files (in .htaccess)