The standard answers are things like, the law exists to protect people, or enforce broadly agreed conduct, or to deter or punish criminals.
Those answers are all wrong. The purpose of the law is this: to convince people not to take matters into their own hands.
Civilization depends on people mostly not taking violent revenge when wronged. The law exists to replace revenge with “justice” in the minds of the aggrieved. Everything else is window dressing.
If this starts to break down then the law is failing. The fix isn’t to convince people that following the law is inportant, the fix is to show people that the law offers a viable notion of justice, whatever that might entail.