2

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?

2
  • Which version of Laravel you are using? Commented Mar 9, 2018 at 5:21
  • Sorry for being late - different time zone and TGIF :) L5.6 Commented Mar 9, 2018 at 22:41

1 Answer 1

3

You can do it like this.

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class SystemEmployeeScope implements Scope
{

    private $user;

    public function __construct()
    {
        $this->user = auth()->user();
    }

    public function apply(Builder $builder, Model $model)
    {
        $userId = $this->user->id
        $builder->where('system_id', $userId);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.