@QasimRashid This is a thing that exists
The 5th Amendment of course is the broadest example of this concept
Section 1915(d) of Title 28 of the United States Code allows federal judges to appoint a lawyer for people who otherwise cannot employ a lawyer.
The Criminal Justice Act allows judges to appoint a lawyer to indigent clients
Many states have similar laws many of which allow courts to compel bar members to represent a client.
There is also a famous supreme court case I cant remember.