The Messenger of Allah ﷺ said, "Actions are judged only by intentions, and each person will have only what they intended. Whoever migrates for the sake of Allah and His Messenger, his migration is for Allah and His Messenger. And whoever migrates for some worldly gain to be acquired or a woman to be married, his migration is for whatever he migrated toward."
حدثنا محمد بن المثنى حدثنا عبد الوهاب الثقفي عن يحيى بن سعيد عن محمد بن إبراهيم عن علقمة بن وقاص الليثي
قال رسول الله ﷺ إنما الأعمال بالنية وإنما لامرئ ما نوى فمن كانت هجرته إلى الله وإلى رسوله فهجرته إلى الله وإلى رسوله ومن كانت هجرته إلى دنيا يصيبها أو امرأة يتزوجها فهجرته إلى ما هاجر إليه
Agreed upon (by Bukhari and Muslim), and Muslim reported it in the Book of Leadership, in the chapter on his saying ﷺ, "Actions are only by intention," and that this includes military expeditions and other deeds, hadith no. 1907, from Muhammad bin Muthanna. Bukhari reported it, hadith no. 6689, from the hadith of Abdul-Wahhab Thaqafi, with the same wording.