Allah Ta‘ala mentions in the story of the people of the Kahf (cave):
اِذِ اعۡتَزَلۡتُمُوۡہُمۡ وَمَا یَعۡبُدُوۡنَ اِلَّا اللّٰہَ فَاۡ وٗۤا اِلَی الۡکَہۡفِ یَنۡشُرۡ لَکُمۡ رَبُّکُمۡ مِّنۡ رَّحۡمَتِہٖ وَیُہَیِّیٔۡ لَکُمۡ مِّنۡ اَمۡرِکُمۡ مِّرۡفَقًا ﴿۱۶﴾
“And when you separate from them and from whatever else they worship besides Allah, then seek refuge in the cave so that your Lord may shower His mercy upon you and He may make your affairs easy for you.” [Surah Kahf v. 16]
This does not necessitate that a person will receive prophethood through solitude, because prophethood is not something that can be earned. Allah Ta‘ala appoints as messenger whomsoever He wishes.
(Extracted from Seeratul Mustafa 1/130-131)