Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/6929370b563ba28b7e3b400b26f22dbb to your computer and use it in GitHub Desktop.
Save yavgel85/6929370b563ba28b7e3b400b26f22dbb to your computer and use it in GitHub Desktop.
Transform brackets into an Eloquent query #laravel #db
<?php
// What if you have and-or mix in your SQL query, like this:
// ... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65) How to translate it into Eloquent?
// This is the wrong way:
$q->where('gender', 'Male');
$q->orWhere('age', '>=', 18);
$q->where('gender', 'Female');
$q->orWhere('age', '>=', 65);
// The order will be incorrect. The right way is a little more complicated, using closure functions as sub-queries:
$q->where(function ($query) {
$query->where('gender', 'Male')
->where('age', '>=', 18);
})->orWhere(function($query) {
$query->where('gender', 'Female')
->where('age', '>=', 65);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment