The ubiquitous, easily torn, often doubled-up plastic bags from the grocery store — hoarded by dog owners, despised by the environmentally concerned and occasionally caught in trees — will soon cost at least a nickel in New York City.

The City Council voted 28 to 20 on Thursday to require certain retailers to collect a fee on each carryout bag, paper or plastic, with some exceptions. Mayor Bill de Blasio has expressed support for the measure.

Passage of the bill came after two years of debate and at least one other attempt by the city’s elected officials to charge a fee or tax on disposable bags. The legislation, modeled on similar laws in California and Washington, D.C., encountered an unusual amount of resistance and resulted in what council members said was one of the closest votes in years, on par with the extension of term limits passed during the tenure of Mr. de Blasio’s predecessor, Michael R. Bloomberg.

The vehemence of the opposition could perhaps be traced to plastic bags’ daily presence in the lives of New Yorkers, who often shop for groceries spontaneously and then lug the crinkly bags home to be reused as trash-can liners or to pick up after pets. As with previous measures adopted by the 51-member Council to prohibit smoking in bars and to include calorie information on restaurant menus, the impact of the bag bill, which would take effect in October, is likely to be immediate for millions of people.