Remember that with the optoisolator, the forward current needs to be limited to 50mA, by a series resistor. The typical forward voltage of the optoisolator input is 1.2V.
If your 5V and 12V sources share a common ground, then the optoisolator is not necessary. Use a regular NPN transistor instead (don't forget the base resistor).