DEV Community

Cover image for How to send SMS Notifications in Laravel using Twilio
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on • Edited on

3 1 1 1 1

How to send SMS Notifications in Laravel using Twilio

Hello Artisans,

In this blog post we will see how we can send sms notifications using laravel.

In Laravel, we can send SMS notifications using a package such as Twilio or Nexmo. In this post we are going to see how we can send SMS using Twilio package.

So let's get started by installing Twilio package:

composer require twilio/sdk
Enter fullscreen mode Exit fullscreen mode

Create a new notification class using the php artisan make:notification command.

php artisan make:notification SendSMS
Enter fullscreen mode Exit fullscreen mode

In the newly created notification class, add a toTwilio method. This method will contain the logic for sending the SMS using the Twilio package.

use Twilio\Rest\Client;

public function toTwilio($notifiable)
{
    $twilio = new Client(env('TWILIO_SID'), env('TWILIO_TOKEN'));

    $message = $twilio->messages
                    ->create("+1234567890", // to
                        array(
                            "body" => "Hello from Laravel!",
                            "from" => "+0987654321"
                        )
                    );
    return $message;
}
Enter fullscreen mode Exit fullscreen mode

In the above code you need to replace TWILIO_SID and TWILIO_TOKEN with your Twilio account SID and token respectively. Also replace the "to" and "from" numbers with the phone numbers you want to send the message to and from.

To send the notification, you can use the Notification facade's send method and pass it the notifiable instance and the notification class.

Notification::send($user, new SendSMS());
Enter fullscreen mode Exit fullscreen mode

Now you can send SMS notification to the user.

Note: You also need to config your Twilio account with phone numbers and other settings.

Thank You!!
Happy Reading 🦄 ❤️

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more