Romans 8:28 tells us, that God works everything for good to them that love Him and are called according to His purpose. Sometimes this seems hard to grasp. It does not seem to make sense in the light of what is happening to us and others in life.
The life of Joseph as recorded in Genesis 37 - 50 did not seem to make sense at the beginning. His brothers were jealous of him because of his father's love for him and the dreams that God gave him concerning his future leadership of them. As a result they set out to destroy him.
First they put him into a pit with the intent to kill him. Then they changed their minds and sold him as a slave. He was taken to Egypt and was resold. God promoted him to become manager of his slave master's estate. His master's wife wanted to have an affair with him, but because of his love and commitment to God he refused and was lied on. As a result he was sentenced to prison falsely for attempting to rape her. God was with him and promoted him to be a superviser in prison. He used his gift of interpriting dreams to interprit the dreams of two of Pharaoh's servants that were in prison. Two years after that he was taken from prison to interprit Pharaoh's dreams. Pharaoh was so inpressed by his wisdom that he promoted him to be governor of Egypt.
Subsequently, there was a famine in the region and Joseph's position made him the savior of his father's household, the Jewish nation, through which Christ came. If Joseph was not in Egypt at the time probably his father's household would have starved to death. But God stragetically used all the evils done to Joseph to trained him and put him in a position of power to save His chosen people through which Christ came to save the world.
Truely, God works all things together for good to them that love Him. As you have seen, Joseph's love for God was demonstrated throughout his sufferings and God worked all things together for good for him.