Ghazni was very proud of the fact that his horoscope matched with the one of Prophet Muhammad. So he thought that just like the prophet, he is born to spread Islam to the world. It is believed that in Mecca, there were 360 idols which were worshipped. Among those there were three goddesses, Al-Lat, Al-Uzza, and Manat. So there was a myth in Arabia that Manat goddess has escaped and gone to India. There was a Persian court poet named Farrukhi Sistani who widely celebrated the demolition of Somnath because the Hindus had occupied the temple. It is also because Manat and Somnath match a lot. However that story is neither mentioned in a primary nor a contemporary source.
The route to Mecca from India was from Somnath so the foreign traders used to see the temple and were quite fascinated by it’s wealth. So Ghazni attacked the temple to steal it’s wealth and destroy the idols. He took the pieces of the idol and placed them under the stairs of the Ghazni Mosque. Khilji also attacked the temple and the idol was taken to Delhi to be broken in front of the crowd.