Where the story is told and the background
Quran 9:40 reminds the believers that Allah had already helped His Prophet ﷺ when those who disbelieved drove him out, "as one of two, when they were in the cave", and he said to his companion not to grieve, for Allah was with them. In Quran 8:30 Allah recalls that the disbelievers plotted to restrain him, kill him or expel him, and says that they plan and Allah plans, and Allah is the best of planners. The Quran does not describe how the plot unfolded.
The details come from hadith. In the long narration of Aisha (may Allah be pleased with her) in Sahih al-Bukhari (3905), the Prophet ﷺ told the Muslims that he had been shown the land of their migration, a land of date palms between two lava fields, and many of them left for Madinah. Abu Bakr prepared to go as well, but the Prophet ﷺ told him to wait, as he hoped to be given permission. So Abu Bakr kept himself ready to accompany him, and fed two mounts for four months.