If the cactus is leaning from the ground, it may be loosely planted in the soil. Improper watering may be the reason. After watering a cactus, the soil must be allowed to completely dry out before watering again. Watering too frequently prevents the soil from hardening around the base of the cactus and causes the soil to loosen. Provided there is no root rot, either transplanting the cactus in dry soil or packing more dirt around it is a solution. Also, adding a layer of small rocks or gravel on the surface can stabilize the cactus.
Even if your cactus is planted in full sun, it may lean. Plants naturally grow toward the sunlight. The barrel cactus grows southward toward the sun so much that it practically lies over on one side. If the cactus is otherwise healthy, this is not a danger. However, if a cactus planted in partial shade is leaning, it may need more sunlight. A cactus in this condition will look sickly and have weak, flimsy stems that are yellow-green. The plant should gradually be exposed to stronger sunlight to prevent sunburn.https://www.gardeningknowhow.com/ornamental/cacti-succulents/barrel-cactus/barrel-cactus-care.htm