Send SMS using TWILIO in Laravel

|
| By Ankush Garg

To put it into action, take the following steps:

  • Install the TWILIO package using the command given below:
    composer require twilio/sdk
  • Now, we require three credentials from the Twilio platform (https://www.twilio.com/console and https://www.twilio.com/console/phone-numbers/incoming).
    • Account SID
    • Auth Token
    • Phone Number
  • Now add these keys to the.env file.
    TWILIO_SID="Account SID" TWILIO_AUTH_TOKEN="Auth Token" TWILIO_NUMBER="Phone Number i.e +19122****"
  • Define a private function as a helper function for sending SMS.
    private function send_message($message, $recipient)
    {
    $account_sid = getenv("TWILIO_SID");
    $auth_token = getenv("TWILIO_AUTH_TOKEN");
    $twilio_number = getenv("TWILIO_NUMBER");
    $client = new Client($account_sid, $auth_token);
    $client->messages->create($recipient,
    ['from' => $twilio_number, 'body' => $message] );
    }
  • Now, we can call the helper function anywhere from the controller:
    $this->send_message('SMS integration implemented successfully !!', “+919876****”);

NOTE: In the case of a test account, you need to verify the recipient’s phone number.

Leave a Reply

Your email address will not be published. Required fields are marked *