When Messenger of Allah ﷺ arrived at Medina, he prayed facing Jerusalem for sixteen or seventeen months but he wished that he would be ordered to face the Kaʿba. So Allah revealed: -- 'Verily! We have seen the turning of your face towards the heaven; surely we shall turn you to a prayer direction (Qibla) that shall please you.' (2.144) Thus he was directed towards the Kaʿba. A man prayed the ʿAsr prayer with the Prophet ﷺ and then went out, and passing by some people from the Ansar, he said, "I testify. that I have prayed with the Prophet ﷺ and he (the Prophet) has prayed facing the Kaʿba." Thereupon they, who were bowing in the ʿAsr prayer, turned towards the Kaʿba.
لَمَّا قَدِمَ رَسُولُ اللَّهِ ﷺ الْمَدِينَةَ صَلَّى نَحْوَ بَيْتِ الْمَقْدِسِ سِتَّةَ عَشَرَ أَوْ سَبْعَةَ عَشَرَ شَهْرًا وَكَانَ يُحِبُّ أَنْ يُوَجَّهَ إِلَى الْكَعْبَةِ فَأَنْزَلَ اللَّهُ تَعَالَى {قَدْ نَرَى تَقَلُّبَ وَجْهِكَ فِي السَّمَاءِ فَلَنُوَلِّيَنَّكَ قِبْلَةً تَرْضَاهَا} فَوُجِّهَ نَحْوَ الْكَعْبَةِ وَصَلَّى مَعَهُ رَجُلٌ الْعَصْرَ ثُمَّ خَرَجَ فَمَرَّ عَلَى قَوْمٍ مِنَ الأَنْصَارِ فَقَالَ هُوَ يَشْهَدُ أَنَّهُ صَلَّى مَعَ النَّبِيِّ ﷺ وَأَنَّهُ قَدْ وُجِّهَ إِلَى الْكَعْبَةِ فَانْحَرَفُوا وَهُمْ رُكُوعٌ فِي صَلاَةِ الْعَصْرِ