Scott Morrison pulled out every trick to avoid a historic loss and in the end he was defeated when Labor decided not to pay some doctors.
Tuesday started with Labor searching for support on its amendments on an asylum seeker medical transfer bill, with the Greens "frustrated" at the last minute changes.
The bill had been amended in the Senate in December, but Labor only decided it needed to make more changes on Monday night, the day before it was due to be voted on.
The proposal called for a specially appointed panel to review medical transfer requests on Manus Island and Nauru, making it harder for the Home Affairs Minister to reject them.
Labor wanted to extend the time frame for the minister to make a decision on a medical transfer from 24 hours to "as soon as practicable".
The party also wanted to expand the grounds the minister can reject a transfer, from national security to include a broader character test.
Greens leader Richard Di Natale went on TV to say his party couldn't support a bill without a clear timeline and he wanted a narrower character test.
Shortly afterwards Labor came back with a 72-hour limit, and a character test that gave the minister tighter powers on who they could reject.
The independents were on board - but then Speaker Tony Smith dropped a bombshell.
He had been given confidential advice from the solicitor-general that the bill was unconstitutional, and also said he had been asked to keep it secret.
Mr Smith tabled it anyway. The advice said the amendment could be unconstitutional because it required public money to pay doctors on the medical panel.
The coalition thought it had a win - until Labor simply decided the doctors would be unpaid.
With the constitutional issue sorted, Labor and the crossbenchers teamed up for a series of 75-74 wins over the coalition.
The amendments passed the lower house on Tuesday evening, and will go to the Senate for approval on Wednesday.
The prime minister confirmed the laws will be given royal assent in the normal way, but he had some parting words for the opposition leader after his government lost a vote on legislation.
"The Australian people have looked at Bill Shorten today and they have found him weak, and he is," Mr Morrison told reporters.
Australian Associated Press