It seems it indeed is a physical punishment as mentioned here:
Washing out mouth with soap is a form of physical punishment that consists in placing soap, or a similar cleansing agent, inside a person's mouth so that the person will taste it, inducing what most people consider an unpleasant experience. One method uses a bar of soap which is placed in a person's mouth; the person can then be forced to hold it for a period of time and/or swallow it. ...
This practice seems to be very old and is related to cleansing someone's bad speech behavior like uttering a profanity, etc.
But going by its impractical approach, it seems it can be used as an idiom when someone gets some sort of an impractical punishment.