mocheaz's avatar

Overriding custom newQuery()

I have a model with a query like this:

class Model extends Eloquent {
    public function newQuery()
    {
        $query = parent::newQuery();
            $query = $query->leftJoin('table2', 'table2.id', '=', 'table1.rel_col_1');
        }
            return $query;
    }
}

But sometimes i need to override this newQuery() and drop the leftJoin();

Is there a way to this?

0 likes
2 replies
acasar's avatar

If you are using Laravel 5.2, you can create a global scope:

class Model extends Eloquent {
    public static function newQuery()
    {
        static::addGlobalScope('join_scope', function($query) {
            $query->leftJoin('table2', 'table2.id', '=', 'table1.rel_col_1');
        });
         parent::boot();
    }
}

Then you can override it as follows:

Model::all(); // includes join
Model::withoutGlobalScope('join_scope')->get(); // doesn't include join
1 like

Please or to participate in this conversation.