Q: “How do we reconcile between the Prophet’s ﷺ prohibition of praying in the graveyard and his praying over the grave of the woman who used to sweep the mosque?”
“There is no contradiction between the two narrations, all praise is due to Allaah. The first narration with the prohibition of praying in the graveyard is like his ﷺ statement in Saheeh Muslim: ‘Don’t sit on graves and don’t pray towards them.’ So the prohibition of praying in the graveyard, i.e. of praying towards the graves, is because prayer must be sincerely for the Face of Allaah تبارك وتعالى without any glorification for other than Allaah mixed in it, as that is a type of shirk. So if a Muslim starts praying to Allaah while facing the grave, there would be a clear suspicion that this person at least intends -as many ignorant people do these days- to seek blessing from this deceased individual through his prayer and through his seeking nearness to Allaah عز وجل with his prayer. Thus he has fallen into some shirk which may get to such a point that it takes him out of the fold of Islaam, wal-`iyaadhu billaah (and refuge is sought in Allaah). This is the meaning that should be considered in regard to the Messenger’s ﷺ prohibition of praying in the graveyard or towards the grave.
As for praying over the deceased while he is in his grave, this is something else. It has nothing to do with praying to Allaah -alone, who has no partner- while facing the grave of the deceased, a prayer whose aim is not so Allaah forgives him, has mercy on him, as is the intent of supplicating over the deceased. Therefore, praying over the deceased while he is in his grave is one thing, and praying to Allaah عز وجل while facing the grave is another thing. The latter is what is prohibited and the former is what is permissible, so there is nothing problematic between the two.”
 Saheeh Muslim 972
[fataawaa jeddah 13 / alalbaany.com]