User::role scope doesn't work inside observer, with teams
jarnesjo opened this issue · 1 comments
Describe the bug
I have enabled teams
and want to add super-admin to every new added company in the app.
My observer for the created
looks like this.
// CompanyObserver.php
public function created(Company $company)
{
// get session team_id for restore it later
$activeCompanyId = getPermissionsTeamId();
// set actual new team_id to package instance
setPermissionsTeamId($company->id);
User::role(RolePermission::SUPER_ADMIN)
->get()
->each(function ($user) {
$user->assignRole(RolePermission::SUPER_ADMIN);
});
// restore session team_id to package instance
setPermissionsTeamId($activeCompanyId);
}
I can confirm it's get called but in the observer User::role(RolePermission::SUPER_ADMIN)->get()
returns[]
.
Outside trying this I get three users so something doesn't work as I thought it should. Maybe missing something essential? If so please enlighten me.
I tried User::find(1)->assignRole(RolePermission::SUPER_ADMIN);
and it's works so it's have to be something with the scope provided.
I have also tried which also returns []
in the observer.
User::whereHas('roles', function ($q) {
$q->where('name', RolePermission::SUPER_ADMIN);
})->get()
Versions
- spatie/laravel-permission: 5.7.0
- laravel/framework: 9.42.2
- laravel/sail: 1.16.3
PHP version: 8.1.12
Expected behavior
Getting the Users with the role SUPER_ADMIN
so it can be assigned that role for the newly created company.
Never mind. I found the solutions of course a couple of minutes after posting here. But after hours of debugging and testing🙄
I have to get the users before starting fiddling with setPermissionsTeamId()
public function created(Company $company)
{
$superadmins = User::role(RolePermission::SUPER_ADMIN)->get();
// get session team_id for restore it later
$activeCompanyId = getPermissionsTeamId();
// set actual new team_id to package instance
setPermissionsTeamId($company->id);
$superadmins->each(function ($user) {
$user->assignRole(RolePermission::SUPER_ADMIN);
});
// restore session team_id to package instance
setPermissionsTeamId($activeCompanyId);
}