There is no direct train service from Porto to Madrid.
In fact at present passenger train services between Portugal and Spain
are not good!
You could get a train from Porto to Coimbra B and then connect with the nightly Lusitânia Comboio Hotel Train at 0:13 (Midnight 13 minutes) and arrive Madrid (Chamartin) at 8.40 the next morning. This is the only rail link.
The quickest way may be by air.
www.ryanair.com fly Porto to Madrid daily.
Bus company www.internorte.pt operate a daily coach service (current timetables) leaving Porto at 09:45 arriving Madrid Est. Sur. at 19:45 Spanish time.
Five nights a week (except Weds./Sat.) there is a service leaving Porto at 20:30 arriving Madrid Est. Sur. at 06:30.