Many scholars have explicitly declared the practice unlawful and have even ruled that any prayer performed there is invalid, although the latter ruling is a matter of dispute.
The point at hand is that, by unanimous agreement, the act is neither obligatory nor recommended; on the contrary, it is unanimously considered reprehensible.
When explaining why prayer in a graveyard is disliked, the jurists mention two reasons. The first is the presumed impurity of the soil, owing to its mixture with the bodily fluids of the deceased; this is the rationale advanced by those who differentiate between old and recent graves. The soundness of this argument is itself disputed, for scholars disagree as to whether grave soil is impure—a question that falls under the broader legal discussion of transformation (istihālah). The majority of Muslim scholars hold that impurity is purified through transformation; this is the position of Abū Ḥanīfah, the Ẓāhirī school, and one of the two opinions reported from Mālik and Aḥmad.
It is authentically established that the Prophet’s Mosque was originally an orchard belonging to Banū al-Najjār containing graves of idolaters, palm-trees, and dilapidated structures. The Prophet, peace and blessings be upon him, ordered the palm-trees cut down, the ruins leveled, and the graves exhumed; the trunks of the palm-trees were then lined up along the qiblah side.