Immediately after the Magi completed their visit to young Jesus and his parents, Joseph and Mary, the Bible records in Matthew chapter 2 that an angel appeared to Joseph in a dream. The angel delivered a warning from God: King Herod, the leader of Judea at the time, had concocted an evil plan to murder Jesus because he was jealous of the threat he thought Jesus would present to his kingdom. Herod had ordered his soldiers to search for Jesus so they could kill the child. To escape, Joseph needed to escort his family to Egypt right away.
The Bible records in Matthew 2:13-15: "When they [the Magi] had gone, an angel of the Lord appeared to Joseph in a dream. 'Get up,' he said, 'take the child and his mother and escape to Egypt. Stay there until I tell you, for Herod is going to search for the child to kill him.' So he got up, took the child and his mother during the night and left for Egypt, where he stayed until the death of Herod. And so was fulfilled what the Lord had said through the prophet: 'Out of Egypt I called my son.'"
Joseph responded to the angel's warning right away; he got up and left with his family during the night, without even waiting for morning to come, leaving his home and friends behind in order to protect Jesus. Joseph's caring concern for Jesus is also evident by the fact that he stayed in Egypt as long as it took to make sure that the threat was completely gone -- when King Herod died (around 4 BC).
The Torah verse that this event fulfills is Hosea 11:1: "When Israel was a child, I loved him,and out of Egypt I called my son."
The story continues in Matthew 2:16-18: "When Herod realized that he had been outwitted by the Magi, he was furious, and he gave orders to kill all the boys in Bethlehem and its vicinity who were two years old and under, in accordance with the time he had learned from the Magi. Then what was said through the prophet Jeremiah was fulfilled: 'A voice is heard in Ramah, weeping and great mourning, Rachel weeping for her children and refusing to be comforted, because they are no more.'"
The verse that Matthew quotes directly is Jeremiah 31:15 of the Torah, which had predicted this tragic event many years before it actually happened. This terrible massacre of young boys is known in history as the Massacre of the Innocents, and it is recorded in a Roman book called The Saturnalia of Macrobius, as well as in the Jewish and Christian apocryphal book The Infancy Gospel of James. King Herod had a reputation for cruelty, and sometimes even killed members of his own family -- but thanks to the angel's warning and Joseph's faithful response, Herod didn't harm Jesus.