0

For some model, I need to apply a global scope if the logged in user is not super admin. In model's boot() method I tried something like this:

<?php

namespace App;

use Auth;
use App\Scopes\RoleScope;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    protected static function boot()
    {
        parent::boot();

        if( Auth::check() && ! Auth::user()->isSuperAdmin() ){
            static::addGlobalScope(new RoleScope);
        }
    }
}

The scop never applied! What did I do wrong here? How can I achieve the goal to apply the scope based on the user role? thanks

Munna Khan
  • 1,902
  • 1
  • 18
  • 24

1 Answers1

0

You cannot access the currently authenticated user in the boot method of the Eloquent model - the Auth middleware hasn't run yet at this point.

What you should do is to perform the super admin check within the apply method of your RoleScope.

Amade
  • 3,665
  • 2
  • 26
  • 54