I needed to make a default global scope for a model using the newQuery()
method.
The Laravel docs say that it's possible in Eloquent to use an anonymous function to group WHERE conditions:
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
But I'm running into something strange when trying that in an overloaded newQuery()
method. For example, let's say I want to do this:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
public function newQuery()
{
return parent::newQuery()->where(function($query) {
$query->where('foreign_id', MyClass::$id)->orWhere('role', 'admin');
});
}
I get a 502 Bad Gateway error! The only way I could figure out how to do a compound WHERE in that method is by doing a raw query:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
public function newQuery()
{
return parent::newQuery()
->whereRaw('(foreign_id = ? or role = ?)')
->setBindings( array( MyClass::$id, 'admin' ) );
}
Does anyone know why that could be happening with Eloquent? It looks like someone else had a slightly different issue with Eloquent in that same method, but there was no definitive answer.