Say, I have 5 systems (lets call them that).
Each system has employees.
When employee from system #1 is logged in, I want to show him list of other employees working for system #1 only.
I wanted to use Global scope.
But I cannot find a way to inject system_id of logged in user.
I tried anonymous global scope - but static boot does cannot accept system_id:
protected static function boot()
{
//this will not work, as scope method is static
$userId = auth()->user()->system_id;
parent::boot();
static::addGlobalScope('thisSystemUser', function (Builder $builder) use($userId) {
$builder->where('system_id', $userId);
});
}
I also tried global scope with separate class - same problem:
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class SystemEmployeeScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
// no luck here as well
$userId = auth()->user()->system_id;
/**
* appended query constraint for this scope
*/
$builder->where('system_id', $userId);
}
}
I tried using $model - to no avail. It returns empty model. Any attempts to get some data via $model also tanked.
I do not want to use local scope, or dynamic scope, as they are not what I want to accomplish and there are better ways, that using these in my case, e.g.: condition directly on relationship - in my case many-to-many.
Is there any way, I am unaware of and not too overly complex to cram that system_id into scope?