Yes, it still costs a spell slot.
The spellcasting rules in the PHB don't address exactly what happens when you cast a spell on a target that can't be affected. However, Xanathar's Guide to Everything (p. 85) provides this guidance for dealing with invalid spell targets (emphasis mine):
A spell specifies what a caster can target with it: any type of creature, a creature of a certain type (humanoid or beast, for instance), an object, an area, the caster, or something else. But what happens if a spell targets something that isn’t a valid target? For example, someone might cast charm person on a creature believed to be a humanoid, not knowing that the target is in fact a vampire. If this issue comes up, handle it using the following rule.
If you cast a spell on someone or something that can’t be affected by the spell, nothing happens to that target, but if you used a spell slot to cast the spell, the slot is still expended. If the spell normally has no effect on a target that succeeds on a saving throw, the invalid target appears to have succeeded on its saving throw, even though it didn’t attempt one (giving no hint that the creature is in fact an invalid target). Otherwise, you perceive that the spell did nothing to the target.
Thus, an easy way to resolve the casting of a spell on a target of the wrong creature type, or one that's immune, is to rule that the casting still expends the spell slot even if it has no effect.
As PJRZ's answer suggests, this encourages spellcasters to think a little bit more carefully about what they're fighting and whether a spell might affect them. At your discretion as the DM, you can ask for an appropriate ability check to determine whether the character would know about such an immunity. Otherwise, as PJRZ says, it's a learning experience; they'll know next time they face such a creature that it can't be charmed.