Muhammad Essam's avatar

Laravel Global scope on inerterOrUpdate

I have an existing code where I'm trying to add multi-tenancy to it. I add a global scope to all models the problem is there exist a lot of code where the method insertOrupdate is updating some settings here is my setup:

trait BelongsToTenant
{
    protected static function bootBelongsToTenant(): void
    {
        static::addGlobalScope(new TenantScope);

        static::creating(function ($model) {
            if (session()->has('tenant_id') and !auth('super')->check() and auth('admin')->check()) {
                $model->tenant_id = session()->get('tenant_id');
            }
        });

    }

    public function tenant()
    {
        return $this->belongsTo(Tenant::class, 'tenant_id');
    }
}

and this is my mdoel setup:

class BusinessSetting extends Model
{
    use BelongsToTenant;

    protected $fillable = ['key', 'value', 'tenant_id'];

}

now the problem is in this code : this is the controller constructor:

 public function __construct(
        private BusinessSetting $business_setting
    ) {
    }

and here is the method update:

 $this->business_setting->updateOrInsert(['key' => 'loyalty_point_status'], [
            'value' => $request['customer_loyalty_point'] ?? 0
        ]);

now I want to apply the global scope so to all insertOrUpdate to by like:

  $this->business_setting->updateOrInsert([
            'key' => 'loyalty_point_status',
            'tenant_id' => session('tenant_id')
        ], [
            'value' => $request['loyalty_point_status'] ?? 0
        ]);

is there any way to do it automatically without manually add the 'tenant_id => session(('tenant_id') to every statment.

0 likes
5 replies
krisi_gjika's avatar

I think updateOrInsert is a method of Database/Builder not Eloquent/Builder. as such it has no functionality of models or scopes as it is closer to a DB::insert call.

I think you might be looking for updateOrCreate method instead.

sheddy714's avatar

Global scores are excellent tools, though, like every tool, they have their place.

I don't know what your global scope does, but if it's causing this much of a headache, you may consider either demoting it to a local scope or reconsidering your implementation https://100001.onl/ .

obada123's avatar

Why not considering Observers

App\Observers\GeneralObserver


class GeneralObserver {

    public function creating($model) {
        $model->tenant_id = session('tenant_id');
    }

}

In your models add the following:


public static function boot() {
        
		parent::boot();

        self::creating(function ($model) {
            (new GeneralObserver())->creating($model);
        });

 }

Muhammad Essam's avatar

@obada123 the problem is with the selecting query to find the right settings, I think there is no way to do it without setting the tenant_id in the updateOrInsert method

Please or to participate in this conversation.