You're most of the way there, and I think you have all of the code you need, but there's a couple of key misconceptions here that are holding you back. Let's start here:
String moodleIdNull = MoodleApiLoaderController.getCoursePortalId(null); //also test ''
String moodleIdExists = MoodleApiLoaderController.getCoursePortalId('...
First, I would recommend that If you are passing an Id to a method, you use the Id type, not the String type. :)
Second, never pass a hardcoded Id to a method... that's just asking for trouble.
Third, you may want to either try-catch the select query or to cast into a List in case the Id does not exist. It is significantly safer.
Having said that, here is ...