Whatever happens here on earth is controlled by Hashem. Some ask the obvious question: If Hashem controls everything, why do bad things happen to good people? We as humans cannot comprehend the reasons that certain things occur, but that doesn't mean that there is no answer. A bad thing that happens at one point could turn out to be something good later on. The story of Yosef provides us with an example of this.
The beginning of Yosef's life seems to be very tragic. He is thrown into a pit by his brothers because of their jealousy. Then some traveling merchants "just happen" to pass by, and Yosef's brothers pull him out of the pit in order to sell him to the merchants. His situation worsens when he is imprisoned after Potifar's wife tries to seduce him. Yosef then "just happens" to meet the wine-steward and the baker, and interpret their dreams. This eventually leads to Yosef's becoming Paroh's viceroy. Because of his stature, Bnai Yisrael come down to Egypt, and he is able to support his family through the famine.
We see that what seem to be a series of tragedies and hardships for Yosef, actually become beneficial for the preservation of Bnai Yisrael. The hand of Hashem was with Yosef the whole time, and His plan unfolded perfectly.