Where does the expression "eat for a cap" or be "a freeloader" come from?

It is a frequent expression, at least in the Spanish spoken in Spain. It is used when someone tries to eat or access a party without paying. So, we say that those came "to eat for free" or were "drinking for free." The expression, quite common today, has an older origin than it seems. In a more derogatory way, when someone does that habitually, they are called "freeloaders".
These two expressions are very common and, while "going cap" does not imply in itself a judgment or criticism, "being a freeloader" is a qualifier that almost implies an insult: the one who takes advantage of others. Both expressions are quite old and could have their origin in Spain in the 16th and 17th centuries, according to Sebastián de Covarrubias. Specifically, it would have arisen in Salamanca, a university city for centuries, and where students had little money to survive.
Like good young men, they had to fend for themselves and have few qualms or shame in doing what was necessary.. And, as young people, instead of wearing a hat, they used to wear a cap. And since hunger sharpens one's wits, students used to try to sneak into banquets and celebrations that took place across the city. In order to enter, they used camaraderie and made grand salutes, cap in hand, to be received. His waving and bowing, cap in hand, was his ticket into the free meal.
At that same time and place, there was the figure of the "capigorrón" (the cape and hat worn by those same students) and that they were students who received compensation for acting as an assistant and sometimes as a servant to other better-positioned students. Their tasks and compensation varied depending on the cases, but they were a kind of subordinates in exchange for food, money or free access to university classes. Its use was shortened to the "freeloader" that we all know today.