I am facing an issue using global scope,
I am working on a multi-tenant application, I need to scope data base on the current tenant/company.
Tenant/Company is in the request which can access like so “request()->company()”
Everything works great with Controllers and Blade, now upgrading my application to Livewire
The scope works very on the first request, I got knock off on subsequent request with this error
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
To reproduce this I have the following
<?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);
}
}
Are you using the latest version of Livewire: Yes ( V2.4.1)
Do you have any screenshots or code examples:
Here is my Trait
<?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)
);
}
}
so basically the active tenant is set in the request so it can be accessed throughout the application like so request()->company()
On first load, everything works fine but thereafter ( hydrate) request()->company() returns null value
Please any advise heads up how to resolve this
Thanks a lot in advance