why in this sentence " Ich esse mit dem Lehrer", it is dem Lehrer instead of den Lehrer?
You have to use the dative case after the preposition "mit". "Der" becomes "dem" in the dative case. "Den", by contrast, is used for the accusative case.
This is a topic that ought to be covered in more depth in the lessons. Each German preposition requires the object to take a specific case (dative, accusative, genitive) and those just need to be memorized.