belongsToMany(Role::class, 'store_user_roles') ->withPivot('store_id') ->withTimestamps(); } /** * Obtener el rol de un usuario en una sucursal específica */ public function getRoleForStore($storeId) { return $this->storeRoles()->wherePivot('store_id', $storeId)->first(); } /** * Verificar si el usuario tiene un rol en una sucursal específica */ public function hasRoleInStore($roleName, $storeId) { return $this->storeRoles() ->wherePivot('store_id', $storeId) ->where('name', $roleName) ->exists(); } /** * Asignar un rol a un usuario en una sucursal específica */ public function assignRoleToStore($roleId, $storeId) { // Verificar si ya tiene el rol en la sucursal if (!$this->hasRoleInStore($roleId, $storeId)) { return $this->storeRoles()->attach($roleId, ['store_id' => $storeId]); } return false; // No hacer nada si ya tiene el rol } /** * Remover un rol de un usuario en una sucursal específica */ public function removeRoleFromStore($roleId, $storeId) { // Verificar si realmente tiene el rol antes de eliminarlo if ($this->hasRoleInStore($roleId, $storeId)) { return $this->storeRoles()->detach($roleId, ['store_id' => $storeId]); } return false; // No hacer nada si no tiene el rol } }