The first report is in al-Bukhārī, and the second in Muslim. Both also appear in the Sunan collections of Abū Dāwūd, al-Nasā’ī, and Ibn Mājah.
Muhammad ibn Sīrīn said:
“The Messenger of Allah, may Allah bless him and grant him peace, used to raise his gaze during prayer. But when this verse was revealed, ‘Successful indeed are the believers, those who are humbly devout in their prayer,’ his gaze would no longer go beyond the place of his prostration.”
Imam Ahmad narrated this in The Book of Abrogating and Abrogated Texts.
Since raising one’s gaze towards heaven is incompatible with humble devotion, the Prophet, may Allah bless him and grant him peace, forbade it and issued a warning against it. Looking aside without need, however, diminishes humble devotion without negating it. It therefore detracts from the prayer, as related by al-Bukhārī, Abū Dāwūd, and al-Nasā’ī from ‘Ā’ishah, may Allah be pleased with her, who said:
“I asked the Messenger of Allah, may Allah bless him and grant him peace, about a man looking aside during prayer. He replied: ‘It is something Satan snatches from the servant’s prayer.’”
Abū Dāwūd and al-Nasā’ī also narrated, through Abū al-Ahwas, from Abū Dharr, may Allah be pleased with him, who said that the Messenger of Allah, may Allah bless him and grant him peace, said:
“Allah remains turned towards His servant while he is praying, so long as he does not look aside. If he looks aside, Allah turns away from him.”
As for looking aside when there is a need, there is nothing wrong with it, as Abū Dāwūd narrated from Sahl ibn al-Hanzaliyyah, who said:
“The call to prayer was made—meaning the dawn prayer—and the Messenger of Allah began