Abdullah bin Mubarak informed us, and the wording is his, from Yahya bin Saeed, from Muhammad bin Ibrahim, from Alqama bin Waqqas, from Umar bin Khattab , who said that the Messenger of Allah ﷺ said, "Actions are judged only by intentions, and every person will receive only what they intended. Whoever's migration was for Allah and His Messenger, their migration was for Allah and His Messenger. And whoever's migration was for some worldly gain to be obtained or a woman to marry, their migration was for whatever they migrated to."
أخبرنا يحيى بن حبيب بن عربي عن حماد والحارث بن مسكين قراءة عليه وأنا أسمع عن ابن القاسم حدثني مالك ح و أخبرنا
أنبأنا عبد الله بن المبارك واللفظ له عن يحيى بن سعيد عن محمد بن إبراهيم عن علقمة بن وقاص عن عمر بن الخطاب رضي الله عنه قال قال رسول الله ﷺ إنما الأعمال بالنية وإنما لامرئ ما نوى فمن كانت هجرته إلى الله وإلى رسوله فهجرته إلى الله وإلى رسوله ومن كانت هجرته إلى دنيا يصيبها أو امرأة ينكحها فهجرته إلى ما هاجر إليه
Agreed upon. Bukhari narrated it in the Book of Faith, chapter on what has been said that deeds are judged by intention and sincere purpose, hadith (54), and Muslim in the Book of Leadership, chapter on his saying that deeds are only by intention, and that this includes military campaigns and other deeds, hadith (1907), from the hadith of Malik through this chain, and it is found in Muwatta, page (403), Nawadir, narration of Muhammad bin Hasan Shaybani, and Kubra (78) (narration of Sulayman bin Mansur only).