1

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?

Warren Sergent
  • 2,542
  • 4
  • 36
  • 42
Julian
  • 111
  • 3
  • 9
  • It's the final methods, get, update, delete, increment etc which determine whether or not it's a select, update, delete etc so unless you can defer the application of the scope then prior to those methods being called, the Builder object is unaware of it's type. This is because the same structure is used for choosing columns in each type of query until the last call whereby Grammar kicks in and builds the right structure. – Ben Swinburne Feb 20 '15 at 14:50
  • Thanks. I ended up using normal Query Scopes since there is no way to detect the type of a query. As in the comment above, the type of query is not applied yet at the time the Scope runs. – Julian Feb 26 '15 at 18:14

0 Answers0