Know if you need to use libsodium at all! Usually, TLS for encryption in transit is enough, but it depends on your use-case. Make sure that you know what is required of your solution and which algorithms are designed to fill these use-cases. (A good example of what not to do is to encrypt something with AES-CBC and believe this means the data can't be modified.)
Secondly, stick to the recipe! With cryptography, it's easy to get things wrong, even if everything seems to work fine.
Finally, have your code audited by a professional auditor. The ability to do so naturally depends on the scope of your project. If it's a hobby project, then it's not necessary to do that, unless having heaps of money laying around is a problem you want to solve.
Securing your Keys
The problem you indicated in your question is that you are unsure how secure the key-material is. In an example, you stated that if an attacker has access to the script that performs the encryption, they could just steal the key and thus decrypt your data. This is correct, which is why you need to implement proper key management.
Doing that is easier said than done, and proper key management could fill books. The extremely simplified version is that keys need to be generated and then stored, until they are finally rolled over and then either archived or destroyed.
If your code is just
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);, what you are doing is literally generating a new key on every call. This might be what you want, but it could also not be what you want. Perhaps you will use that key as a DEK and encrypt it with a public key, or you will send it to the user, or do any number of things with it. Perhaps you would rather derive that key from a password that the user has inputted. You have to know these things beforehand, and make sure you use the right cryptographic primitives.
Securing your Server
It's vitally important that you secure whichever platform you use to store your keys. If an attacker can gain access to the server that runs your crypto, then you can pack up and go home, because the game is over. It is absolutely vital to ensure that an attacker has no way of running their code on your servers, or has any other way to get even a hint at the key material you use.
If you, for instance, store your keys in a 32-byte wide database field, and an attacker can read out your database, then all keys have been leaked.
Crypto is hard, so the less of it that you need to do yourself, the better. Check if you actually need to write crypto-code yourself. If not, don't do it.
Read up on key management, and make sure you have strategies on what to do if things go wrong.
Secure your server, because if it's compromised, you have lost.