The production of anticompetitor toxins is widespread among bacteria. Because production of such toxins is costly, it is typically regulated. In particular, many toxins are produced only when the local cell density is high. It is unclear which selection pressures shaped the evolution of density-dependent regulation of toxin production. Here, we study the evolution of toxin production, resistance and the response to a cell-density cue in a model of an evolving bacterial population with spatial structure. We present results for two growth regimes: (i) an undisturbed, fixed habitat in which only small fluctuations of cell density occur, and (ii) a serial-transfer regime with large fluctuations in cell density. We find that density-dependent toxin production can evolve under both regimes. However, the selection pressures driving the evolution of regulation differ. In the fixed habitat, regulation evolves because it allows cells to produce toxin only when opportunities for reproduction are highly limited (because of a high local cell density), and the effective fitness costs of toxin production are hence low. Under serial transfers, regulation evolves because it allows cells to switch from a fast-growing non-toxic phenotype when colonising a new habitat, to a slower-growing competitive toxic phenotype when the cell density increases. Colonies of such regulating cells rapidly expand into unoccupied space because their edges consist of fast-growing, non-toxin-producing cells, but are also combative because cells at the interfaces with competing colonies do produce toxin. Because under the two growth regimes different types of regulation evolve, our results underscore the importance of growth conditions in the evolution of social behaviour in bacteria.