Ad

Query Scope Using OrWhere In Laravel 5.2

Using Laravel 5.2, I have the following query scope on my model:

public function scopeInProcess($query) {
    return $query->whereHas(
        'ApplicationStatus', function($query) {
            $query->whereRaw('(name = "New" OR name = "In-process")');
        }
    );
}

The above works fine, but I only started using whereRaw() because I couldn't get orWhere() to work as described in the docs.

As far as I can tell, this should do exactly the same thing as whereRaw():

$query->where('name', 'New')->orWhere('name' , 'In-process');

It doesn't work, though. It just returns all of the records, including ones with other status names.

Ad

Answer

It's not doing the exact same thing. In your whereRaw(), you've wrapped both conditions in parentheses, to group them together. This is what you want. However, the where()->orWhere() does not automatically do this.

To get your desired functionality, you need to group your conditions, as you did in the whereRaw(). You do this by passing a closure to the where() method, like so:

public function scopeInProcess($query) {
    return $query->whereHas('ApplicationStatus', function($query) {
        $query->where(function($q) {
            $q->where('name', 'New')->orWhere('name', 'In-process');
        });
    });
}
Ad
source: stackoverflow.com
Ad