كتاب الْمَسَاجِدِ وَمَوَاضِعِ الصَّلاَةِ
5
The Book of Mosques and Places of Prayer
(17)
Chapter: Prohibiting one who has eaten garlic, onions, or leeks, and other things that have an offensive odor from coming to the masjid, until that smell has gone away, and such a person should be expelled from the masjid
(17)
باب نَهْىِ مَنْ أَكَلَ ثُومًا أَوْ بَصَلاً أَوْ كُرَّاثًا أَوْ نَحْوَهَا عَنْ حُضُورِ الْمَسْجِدِ ‏‏

Abu Sa'id reported:

We made no transgression but Khaybar was conquered. We, the Companions of the Messenger of Allah (ﷺ), fell upon this plant. i e. garlic. because the people were hungry. We ate it to our heart's content and then made our way towards the mosque. The Messenger of Allah (ﷺ) sensed its odour and he said: He who takes anything of this offensive plant must not approach us in the mosque. The people said: Its (use) has been forbidden; its (use) bu been forbidden. This reached the Messenger of Allah (ﷺ) and he said: O people, I cannot forbid (the use of a thing) which Allah has made lawful, but (this garlic) is a plant the odour of which is repugnant to me.
وَحَدَّثَنِي عَمْرٌو النَّاقِدُ، حَدَّثَنَا إِسْمَاعِيلُ ابْنُ عُلَيَّةَ، عَنِ الْجُرَيْرِيِّ، عَنْ أَبِي نَضْرَةَ، عَنْ أَبِي سَعِيدٍ، قَالَ لَمْ نَعْدُ أَنْ فُتِحَتْ، خَيْبَرُ فَوَقَعْنَا أَصْحَابَ رَسُولِ اللَّهِ صلى الله عليه وسلم فِي تِلْكَ الْبَقْلَةِ الثُّومِ وَالنَّاسُ جِيَاعٌ فَأَكَلْنَا مِنْهَا أَكْلاً شَدِيدًا ثُمَّ رُحْنَا إِلَى الْمَسْجِدِ فَوَجَدَ رَسُولُ اللَّهِ صلى الله عليه وسلم الرِّيحَ فَقَالَ ‏"‏ مَنْ أَكَلَ مِنْ هَذِهِ الشَّجَرَةِ الْخَبِيثَةِ شَيْئًا فَلاَ يَقْرَبَنَّا فِي الْمَسْجِدِ ‏"‏ ‏.‏ فَقَالَ النَّاسُ حُرِّمَتْ حُرِّمَتْ ‏.‏ فَبَلَغَ ذَاكَ النَّبِيَّ صلى الله عليه وسلم فَقَالَ ‏"‏ أَيُّهَا النَّاسُ إِنَّهُ لَيْسَ بِي تَحْرِيمُ مَا أَحَلَّ اللَّهُ لِي وَلَكِنَّهَا شَجَرَةٌ أَكْرَهُ رِيحَهَا ‏"‏ ‏.‏
Reference : Sahih Muslim 565
In-book reference : Book 5, Hadith 94
USC-MSA web (English) reference : Book 4, Hadith 1149
  (deprecated numbering scheme)