First: make sure the cable is OK. If possible, try another cable or check, with the same cable and the original charger, if charging works or also keeps turning on/off. If on/off as well, your cable is probably wrong.
Second: check for dirt in the iPhones charging port. If dirty, carefully try to clean the charging port.
Third: disconnect your iPhone from your Mac, start Terminal and issue this command:
sudo killall -STOP -c usbd
If asked for a password, enter the one you use when you start your Mac.
Next issue the command (again in Terminal):
sudo killall -CONT usbd
Re-connect your iPhone to your Mac and check if it works now.
If still not, try another USB port on your Mac.
If it then still not works, then it's likely either your iPhone, the cable or your Mac has a hardware issue.