18m diffuse PNP photoelectric sensor and arduino
simulate this circuit &ndash; Schematic created using CircuitLab

Figure 1. (a) is what you seem to have done. (b) is the equivalent circuit which should make it clear that you have fed 12 V into the microcontroller input. (c) is the solution.

R1 and R2 form a 12:5 potential divider which reduces the 12 V to 5 V level compatible with the micro. You can select any resistor combination to give the ratio but ratio values in the 1k to 100k range should be fine. If I suspected that the 12 V supply could rise above 12 V I would reduce the ratio further to protect the input of the micro. D1 protects it in the event of a gross overload by diverting current to the 5 V supply. This limits the input voltage to about 5.6 V max.