When Earth formed, it created its own gravitational force, enhanced by spinning, or rotating.
This kept the collected material together. Without the Sun’s gravity, Earth would go spinning off into space, but without Earth’s own gravity in conjunction with the gravitational force from other planets, it would be drawn into the Sun.
So, while the Sun pulls Earth toward it, the cumulative gravity of Earth and the other planets keeps it in its orbit around the Sun. Think of it as a multiple tug-of-war.