Social environment modulates learning through unknown mechanisms. Here, we report that a pheromone mixture that signals overcrowding inhibits C. elegans from learning to avoid pathogenic bacteria. We find that learning depends on the balanced signaling of two insulin-like peptides (ILPs), INS-16 and INS-4, which act respectively in the pheromone-sensing neuron ADL and the bacteria-sensing neuron AWA. Pheromone exposure inhibits learning by disrupting this balance: it activates ADL and increases expression of ins-16, and this cellular effect reduces AWA activity and AWA-expressed ins-4. The activities of the sensory neurons are required for learning and the expression of the ILPs. Interestingly, pheromones also promote the ingestion of pathogenic bacteria while increasing resistance to the pathogen. Thus, the balance of the ILP signals integrates social information into the learning process as part of a coordinated adaptive response that allows consumption of harmful food during times of high population density.