I want to use an Eloquent Global Scope that will add a join to every select query for some models. The problem I'm facing is that the join is also added on other statements like UPDATE for example which makes the query invalid.
The main idea for the functionality I want is that after login, some models will only return the data the logged in user has access to (transparently for the developer because this join will be added in the background by using global scopes and traits).
So, instead of using something like User::accessible()->get(), I would like to use User::get() and the "accessible" scope should be added globally, based on some conditions...
This is the apply method of the ScopeInterface:
public function apply(Builder $builder)
{
$table = $builder->getModel()->getTable();
$companyLevel = $builder->getModel()->_getCompanyLevel();
//I would like to detect if this is a SELECT query here, somehow...
if ($companyLevel !== null) {
$columns = $builder->getQuery()->columns;
//if all columns or no specified columns
if((count($columns)==1 && $columns[0]=='*') || count($columns)==0) {
$builder->getQuery()->select([$table.'.*']);
}
$builder->getQuery()
->join('spaces',$table.'.space_id','=','spaces.id')
->where('spaces.level','>',$companyLevel);
}
}
Any ideas on how to detect a SELECT query?