首页 > 解决方案 > Laravel Livewire,初始请求后的全局范围错误

问题描述

我在使用全局范围时遇到问题,我正在开发一个多租户应用程序,我需要根据当前租户/公司来确定数据库范围。租户/公司在请求中,可以像这样访问request()->company()

Controllers 和 Blade 一切正常,现在将我的应用程序升级到 Livewire

TypeError
Argument 1 passed to App\Tenant\Scope\TenantScope::__construct() must be an instance of 
Illuminate\Database\Eloquent\Model, null given, called in 
D:\laragon\www\vistate\app\Tenant\Traits\ForTenants.php on line 19 

为了重现这一点,我有以下

<?php

    namespace App\Tenant\Scope;

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

    class TenantScope implements Scope
    {
        protected $company;

        public function __construct (Model $company)
        {
            $this->company = $company;
        }

        public function apply(Builder $builder, Model $model)
        {
            return $builder->where($this->company->getForeignKey(), '=', $this->company->id);
        }
    }

Livewire 版本 2.4.1

这是我的特质

    <?php

    namespace App\Tenant\Traits;

    use App\Tenant\Observers\TenantObserver;
    use App\Tenant\Scope\TenantScope;
    use App\Tenant\Manager;

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

            $manager = app(Manager::class);


            static::addGlobalScope(
              new TenantScope($manager->getCompany())
            );

            static::observe(
                app(TenantObserver::class)
            );
        }

    }

所以基本上活动租户是在请求中设置的,因此可以在整个应用程序中访问它,就像这样request()->company() 在第一次加载时,一切正常,但此后(水合物)request()->company()返回空值

请任何建议抬头如何解决这个问题

非常感谢提前

标签: phplaraveleloquentlaravel-livewire

解决方案


protected $company; 
public function __construct (Model $company) 
{ 
      $this->company = $company; 
} 
public function apply(Builder $builder, Model $model) 
{ 
      return $builder->where($this->company->getForeignKey(), '=', $this->company->id); 
}

检查这2件事。尝试更改受保护以公开公司财产。在 Livewire 中,据我所知,protected 和 private 不会持久化数据。在 apply 方法中(也许这无关紧要,但已检查)您与同一公司实例进行比较

public function apply(Builder $builder, Model $model) 
{ 
      return $builder->where($this->company->getForeignKey(), '=', $this->company->id); 
}

我认为您需要比较 $this->company->getForeignKey(), '=', $model->id,因为您将 $model 实例作为参数传递?


推荐阅读