Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nvangijzen's avatar

Overloading newQuery and put the rest of the query in scope

I'm working on an application where a lot of models have a Company Filter which looks a bit like:

public function newQuery($excludeDeleted = true) {

    $query = parent::newQuery($excludeDeleted);
    if (!authUserIsAdmin()) {
        $query->where('company_id', Auth::user()->company_id);
    }

    return $query;
    }

But now if we use an orWhere clause in our queries the company_id part is bypassed by the OR clause. Is there a way to put the whole query to come in a scope (between parentheses) and combine that with an AND company_id = ? at the end?

0 likes
1 reply
lostdreamer_nl's avatar
Level 53

use a globalScope (they get added to the query at the last moment)

protected static function boot()
{
    parent::boot();
    static::addGlobalScope('owner', function(Builder $builder) {
        $builder->where('owner_id', '!=' ,null);
    });
}

$trips = Trip::where('owner_type', '!=', '')->orWhere('connection_id', '!=', '')->toSql();

// "select * from `trips` where (`owner_type` != '' or `connection_id` != '') and `owner_id` is not null"

Please or to participate in this conversation.