Now when they had departed, behold, an angel of the Lord appeared to Joseph in a dream, saying, “Arise, take the young Child and His mother, flee to Egypt, and stay there until I bring you word; for Herod will seek the young Child to destroy Him.” When he arose, he took the young Child and His mother by night and departed for Egypt, and was there until the death of Herod, that it might be fulfilled which was spoken by the Lord through the prophet, saying, “Out of Egypt I called My Son.”
As we saw in the commentary on Matthew 2:4-6, paranoid King Herod felt threatened when he heard about the wise men’s search for the Messiah. God warned the wise men in a dream not to go back to Herod, and the king became furious (Matthew 2:12, 16). He set out to remove any potential threat to his throne by killing all the boys age 2 and under.
But God had long foreseen Herod’s (and Satan’s, Revelation 12:4-5) plot, and instructed Joseph in another dream to flee to Egypt. This was a fulfillment of the dual prophecy of Hosea 11:1.