After the wise men were gone, an angel of the Lord appeared to Joseph in a dream. "Get up and flee to Egypt with the child and his mother," the angel said. "Stay there until I tell you to return, because Herod is going to try to kill the child."
That night Joseph left for Egypt with the child and Mary, his mother,
and they stayed there until Herod's death. This fulfilled what the Lord had spoken through the prophet: "I called my Son out of Egypt."
References for Matthew 2:15
Herod was furious when he learned that the wise men had outwitted him. He sent soldiers to kill all the boys in and around Bethlehem who were two years old and under, because the wise men had told him the star first appeared to them about two years earlier.
References for Matthew 2:16
Herod's brutal action fulfilled the prophecy of Jeremiah:
"A cry of anguish is heard in Ramah -- weeping and mourning unrestrained. Rachel weeps for her children, refusing to be comforted -- for they are dead."
References for Matthew 2:18
When Herod died, an angel of the Lord appeared in a dream to Joseph in Egypt and told him,
"Get up and take the child and his mother back to the land of Israel, because those who were trying to kill the child are dead."
So Joseph returned immediately to Israel with Jesus and his mother.
But when he learned that the new ruler was Herod's son Archelaus, he was afraid. Then, in another dream, he was warned to go to Galilee.
So they went and lived in a town called Nazareth. This fulfilled what was spoken by the prophets concerning the Messiah: "He will be called a Nazarene."