Hello guys,
So I'm in a cat-chasing-tail situation. I'm defining global scopes depending on the content of a session variable :
protected static function booted()
{
if(session()->has('organization')) {
static::addGlobalScope(new OrganizationScope);
}
}
This session value is set using login events (thanks @kreierson). So, in tests, I will have to use $this->actingAs($user)->withSession(['organization' => $organization]); where relevant, right? Sure, this works.
But now, when creating my data for tests with factories, the scope is applied. Moreover, as I'm connected as a specific user, other things are automatically set up that I don't want. So I want to prepare my date before calling actingAs. That's what I did.
The issue is, when I do that, the booted function of the model is called when creating the data and never again. That means the if statement checking if there is an organization variable in the session is always false, even after I called the actingAs...withSession.
So, a couple question:
1/ Is it possible to have those booted, booting etc... Be reinintialized on demand?
2/ Is it bad practice to have conditions in there? I could put the condition in the OrganizationScope code, of course, but then I would add the scope to every models even for people not needing it (and the scope wouldn't change anything then of course)... Not clean, I think.
3/ Do you have a better approach to recommend?
Thanks ahead!