The Messenger of Allah ﷺ said, "Actions are judged only by intentions, and every person will be rewarded according to what he intended. So whoever migrated for the sake of Allah and His Messenger, his migration was for Allah and His Messenger. And whoever migrated for some worldly gain he sought to acquire or a woman he wished to marry, his migration was for whatever he migrated for."
حدثنا محمد بن كثير أخبرنا سفيان حدثني يحيى بن سعيد عن محمد بن إبراهيم التيمي عن علقمة بن وقاص الليثي قال سمعت
قال رسول الله ﷺ إنما الأعمال بالنيات وإنما لكل امرئ ما نوى فمن كانت هجرته إلى الله ورسوله فهجرته إلى الله ورسوله ومن كانت هجرته لدنيا يصيبها أو امرأة يتزوجها فهجرته إلى ما هاجر إليه
Bukhari narrated it in the Book of the Beginning of Revelation, Chapter on How the Revelation Began to the Messenger of Allah ﷺ, etc., hadith no. 1, and Muslim narrated it in the Book of Leadership, Chapter on his ﷺ saying, "Actions are only by intention," etc., hadith no. 1907, from the hadith of Sufyan bin Uyayna, through the same chain.